#![allow(clippy::ptr_arg)]
use std::collections::{BTreeSet, HashMap};
use tokio::time::sleep;
// ##############
// UTILITIES ###
// ############
/// Identifies the an OAuth2 authorization scope.
/// A scope is needed when requesting an
/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
pub enum Scope {
/// View and manage your data across Google Cloud Platform services
CloudPlatform,
/// View your data across Google Cloud Platform services
CloudPlatformReadOnly,
/// Manage your data and permissions in Google Cloud Storage
DevstorageFullControl,
/// View your data in Google Cloud Storage
DevstorageReadOnly,
/// Manage your data in Google Cloud Storage
DevstorageReadWrite,
}
impl AsRef<str> for Scope {
fn as_ref(&self) -> &str {
match *self {
Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
Scope::CloudPlatformReadOnly => {
"https://www.googleapis.com/auth/cloud-platform.read-only"
}
Scope::DevstorageFullControl => {
"https://www.googleapis.com/auth/devstorage.full_control"
}
Scope::DevstorageReadOnly => "https://www.googleapis.com/auth/devstorage.read_only",
Scope::DevstorageReadWrite => "https://www.googleapis.com/auth/devstorage.read_write",
}
}
}
#[allow(clippy::derivable_impls)]
impl Default for Scope {
fn default() -> Scope {
Scope::CloudPlatform
}
}
// ########
// HUB ###
// ######
/// Central instance to access all Storage related resource activities
///
/// # Examples
///
/// Instantiate a new hub
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_storage1 as storage1;
/// use storage1::{Result, Error};
/// # async fn dox() {
/// use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
/// // `client_secret`, among other things.
/// let secret: yup_oauth2::ApplicationSecret = Default::default();
/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
/// // unless you replace `None` with the desired Flow.
/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
/// // retrieve them from storage.
/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_only()
/// .enable_http2()
/// .build();
///
/// let executor = hyper_util::rt::TokioExecutor::new();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// yup_oauth2::client::CustomHyperClientBuilder::from(
/// hyper_util::client::legacy::Client::builder(executor).build(connector),
/// ),
/// ).build().await.unwrap();
///
/// let client = hyper_util::client::legacy::Client::builder(
/// hyper_util::rt::TokioExecutor::new()
/// )
/// .build(
/// hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_or_http()
/// .enable_http2()
/// .build()
/// );
/// let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().list("project")
/// .user_project("duo")
/// .soft_deleted(true)
/// .return_partial_success(false)
/// .projection("ut")
/// .prefix("gubergren")
/// .page_token("rebum.")
/// .max_results(44)
/// .doit().await;
///
/// match result {
/// Err(e) => match e {
/// // The Error enum provides details about what exactly happened.
/// // You can also just use its `Debug`, `Display` or `Error` traits
/// Error::HttpError(_)
/// |Error::Io(_)
/// |Error::MissingAPIKey
/// |Error::MissingToken(_)
/// |Error::Cancelled
/// |Error::UploadSizeLimitExceeded(_, _)
/// |Error::Failure(_)
/// |Error::BadRequest(_)
/// |Error::FieldClash(_)
/// |Error::JsonDecodeError(_, _) => println!("{}", e),
/// },
/// Ok(res) => println!("Success: {:?}", res),
/// }
/// # }
/// ```
#[derive(Clone)]
pub struct Storage<C> {
pub client: common::Client<C>,
pub auth: Box<dyn common::GetToken>,
_user_agent: String,
_base_url: String,
_root_url: String,
}
impl<C> common::Hub for Storage<C> {}
impl<'a, C> Storage<C> {
pub fn new<A: 'static + common::GetToken>(client: common::Client<C>, auth: A) -> Storage<C> {
Storage {
client,
auth: Box::new(auth),
_user_agent: "google-api-rust-client/7.0.0".to_string(),
_base_url: "https://storage.googleapis.com/storage/v1/".to_string(),
_root_url: "https://storage.googleapis.com/".to_string(),
}
}
pub fn anywhere_caches(&'a self) -> AnywhereCachMethods<'a, C> {
AnywhereCachMethods { hub: self }
}
pub fn bucket_access_controls(&'a self) -> BucketAccessControlMethods<'a, C> {
BucketAccessControlMethods { hub: self }
}
pub fn buckets(&'a self) -> BucketMethods<'a, C> {
BucketMethods { hub: self }
}
pub fn channels(&'a self) -> ChannelMethods<'a, C> {
ChannelMethods { hub: self }
}
pub fn default_object_access_controls(&'a self) -> DefaultObjectAccessControlMethods<'a, C> {
DefaultObjectAccessControlMethods { hub: self }
}
pub fn folders(&'a self) -> FolderMethods<'a, C> {
FolderMethods { hub: self }
}
pub fn managed_folders(&'a self) -> ManagedFolderMethods<'a, C> {
ManagedFolderMethods { hub: self }
}
pub fn notifications(&'a self) -> NotificationMethods<'a, C> {
NotificationMethods { hub: self }
}
pub fn object_access_controls(&'a self) -> ObjectAccessControlMethods<'a, C> {
ObjectAccessControlMethods { hub: self }
}
pub fn objects(&'a self) -> ObjectMethods<'a, C> {
ObjectMethods { hub: self }
}
pub fn projects(&'a self) -> ProjectMethods<'a, C> {
ProjectMethods { hub: self }
}
/// Set the user-agent header field to use in all requests to the server.
/// It defaults to `google-api-rust-client/7.0.0`.
///
/// Returns the previously set user-agent.
pub fn user_agent(&mut self, agent_name: String) -> String {
std::mem::replace(&mut self._user_agent, agent_name)
}
/// Set the base url to use in all requests to the server.
/// It defaults to `https://storage.googleapis.com/storage/v1/`.
///
/// Returns the previously set base url.
pub fn base_url(&mut self, new_base_url: String) -> String {
std::mem::replace(&mut self._base_url, new_base_url)
}
/// Set the root url to use in all requests to the server.
/// It defaults to `https://storage.googleapis.com/`.
///
/// Returns the previously set root url.
pub fn root_url(&mut self, new_root_url: String) -> String {
std::mem::replace(&mut self._root_url, new_root_url)
}
}
// ############
// SCHEMAS ###
// ##########
/// An AdvanceRelocateBucketOperation request.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [operations advance relocate bucket buckets](BucketOperationAdvanceRelocateBucketCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AdvanceRelocateBucketOperationRequest {
/// Specifies the time when the relocation will revert to the sync stage if the relocation hasn't succeeded.
#[serde(rename = "expireTime")]
pub expire_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// Specifies the duration after which the relocation will revert to the sync stage if the relocation hasn't succeeded. Optional, if not supplied, a default value of 12h will be used.
#[serde_as(as = "Option<common::serde::duration::Wrapper>")]
pub ttl: Option<chrono::Duration>,
}
impl common::RequestValue for AdvanceRelocateBucketOperationRequest {}
/// An Anywhere Cache instance.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [disable anywhere caches](AnywhereCachDisableCall) (response)
/// * [get anywhere caches](AnywhereCachGetCall) (response)
/// * [insert anywhere caches](AnywhereCachInsertCall) (request)
/// * [list anywhere caches](AnywhereCachListCall) (none)
/// * [pause anywhere caches](AnywhereCachPauseCall) (response)
/// * [resume anywhere caches](AnywhereCachResumeCall) (response)
/// * [update anywhere caches](AnywhereCachUpdateCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AnywhereCache {
/// The cache-level entry admission policy.
#[serde(rename = "admissionPolicy")]
pub admission_policy: Option<String>,
/// The ID of the Anywhere cache instance.
#[serde(rename = "anywhereCacheId")]
pub anywhere_cache_id: Option<String>,
/// The name of the bucket containing this cache instance.
pub bucket: Option<String>,
/// The creation time of the cache instance in RFC 3339 format.
#[serde(rename = "createTime")]
pub create_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The ID of the resource, including the project number, bucket name and anywhere cache ID.
pub id: Option<String>,
/// The kind of item this is. For Anywhere Cache, this is always storage#anywhereCache.
pub kind: Option<String>,
/// True if the cache instance has an active Update long-running operation.
#[serde(rename = "pendingUpdate")]
pub pending_update: Option<bool>,
/// The link to this cache instance.
#[serde(rename = "selfLink")]
pub self_link: Option<String>,
/// The current state of the cache instance.
pub state: Option<String>,
/// The TTL of all cache entries in whole seconds. e.g., "7200s".
#[serde_as(as = "Option<common::serde::duration::Wrapper>")]
pub ttl: Option<chrono::Duration>,
/// The modification time of the cache instance metadata in RFC 3339 format.
#[serde(rename = "updateTime")]
pub update_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The zone in which the cache instance is running. For example, us-central1-a.
pub zone: Option<String>,
}
impl common::RequestValue for AnywhereCache {}
impl common::Resource for AnywhereCache {}
impl common::ResponseResult for AnywhereCache {}
/// A list of Anywhere Caches.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [list anywhere caches](AnywhereCachListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AnywhereCaches {
/// The list of items.
pub items: Option<Vec<AnywhereCache>>,
/// The kind of item this is. For lists of Anywhere Caches, this is always storage#anywhereCaches.
pub kind: Option<String>,
/// The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
}
impl common::ResponseResult for AnywhereCaches {}
/// A bucket.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [delete buckets](BucketDeleteCall) (none)
/// * [get buckets](BucketGetCall) (response)
/// * [get iam policy buckets](BucketGetIamPolicyCall) (none)
/// * [get storage layout buckets](BucketGetStorageLayoutCall) (none)
/// * [insert buckets](BucketInsertCall) (request|response)
/// * [list buckets](BucketListCall) (none)
/// * [lock retention policy buckets](BucketLockRetentionPolicyCall) (response)
/// * [patch buckets](BucketPatchCall) (request|response)
/// * [relocate buckets](BucketRelocateCall) (none)
/// * [restore buckets](BucketRestoreCall) (response)
/// * [set iam policy buckets](BucketSetIamPolicyCall) (none)
/// * [test iam permissions buckets](BucketTestIamPermissionCall) (none)
/// * [update buckets](BucketUpdateCall) (request|response)
/// * [operations advance relocate bucket buckets](BucketOperationAdvanceRelocateBucketCall) (none)
/// * [operations cancel buckets](BucketOperationCancelCall) (none)
/// * [operations get buckets](BucketOperationGetCall) (none)
/// * [operations list buckets](BucketOperationListCall) (none)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Bucket {
/// Access controls on the bucket.
pub acl: Option<Vec<BucketAccessControl>>,
/// The bucket's Autoclass configuration.
pub autoclass: Option<BucketAutoclass>,
/// The bucket's billing configuration.
pub billing: Option<BucketBilling>,
/// The bucket's Cross-Origin Resource Sharing (CORS) configuration.
pub cors: Option<Vec<BucketCors>>,
/// The bucket's custom placement configuration for Custom Dual Regions.
#[serde(rename = "customPlacementConfig")]
pub custom_placement_config: Option<BucketCustomPlacementConfig>,
/// The default value for event-based hold on newly created objects in this bucket. Event-based hold is a way to retain objects indefinitely until an event occurs, signified by the hold's release. After being released, such objects will be subject to bucket-level retention (if any). One sample use case of this flag is for banks to hold loan documents for at least 3 years after loan is paid in full. Here, bucket-level retention is 3 years and the event is loan being paid in full. In this example, these objects will be held intact for any number of years until the event has occurred (event-based hold on the object is released) and then 3 more years after that. That means retention duration of the objects begins from the moment event-based hold transitioned from true to false. Objects under event-based hold cannot be deleted, overwritten or archived until the hold is removed.
#[serde(rename = "defaultEventBasedHold")]
pub default_event_based_hold: Option<bool>,
/// Default access controls to apply to new objects when no ACL is provided.
#[serde(rename = "defaultObjectAcl")]
pub default_object_acl: Option<Vec<ObjectAccessControl>>,
/// Encryption configuration for a bucket.
pub encryption: Option<BucketEncryption>,
/// HTTP 1.1 Entity tag for the bucket.
pub etag: Option<String>,
/// The generation of this bucket.
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub generation: Option<i64>,
/// The hard delete time of the bucket in RFC 3339 format.
#[serde(rename = "hardDeleteTime")]
pub hard_delete_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The bucket's hierarchical namespace configuration.
#[serde(rename = "hierarchicalNamespace")]
pub hierarchical_namespace: Option<BucketHierarchicalNamespace>,
/// The bucket's IAM configuration.
#[serde(rename = "iamConfiguration")]
pub iam_configuration: Option<BucketIamConfiguration>,
/// The ID of the bucket. For buckets, the id and name properties are the same.
pub id: Option<String>,
/// The bucket's IP filter configuration. Specifies the network sources that are allowed to access the operations on the bucket, as well as its underlying objects. Only enforced when the mode is set to 'Enabled'.
#[serde(rename = "ipFilter")]
pub ip_filter: Option<BucketIpFilter>,
/// The kind of item this is. For buckets, this is always storage#bucket.
pub kind: Option<String>,
/// User-provided labels, in key/value pairs.
pub labels: Option<HashMap<String, String>>,
/// The bucket's lifecycle configuration. See [Lifecycle Management](https://cloud.google.com/storage/docs/lifecycle) for more information.
pub lifecycle: Option<BucketLifecycle>,
/// The location of the bucket. Object data for objects in the bucket resides in physical storage within this region. Defaults to US. See the [Developer's Guide](https://cloud.google.com/storage/docs/locations) for the authoritative list.
pub location: Option<String>,
/// The type of the bucket location.
#[serde(rename = "locationType")]
pub location_type: Option<String>,
/// The bucket's logging configuration, which defines the destination bucket and optional name prefix for the current bucket's logs.
pub logging: Option<BucketLogging>,
/// The metadata generation of this bucket.
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub metageneration: Option<i64>,
/// The name of the bucket.
pub name: Option<String>,
/// The bucket's object retention config.
#[serde(rename = "objectRetention")]
pub object_retention: Option<BucketObjectRetention>,
/// The owner of the bucket. This is always the project team's owner group.
pub owner: Option<BucketOwner>,
/// The project number of the project the bucket belongs to.
#[serde(rename = "projectNumber")]
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub project_number: Option<u64>,
/// The bucket's retention policy. The retention policy enforces a minimum retention time for all objects contained in the bucket, based on their creation time. Any attempt to overwrite or delete objects younger than the retention period will result in a PERMISSION_DENIED error. An unlocked retention policy can be modified or removed from the bucket via a storage.buckets.update operation. A locked retention policy cannot be removed or shortened in duration for the lifetime of the bucket. Attempting to remove or decrease period of a locked retention policy will result in a PERMISSION_DENIED error.
#[serde(rename = "retentionPolicy")]
pub retention_policy: Option<BucketRetentionPolicy>,
/// The Recovery Point Objective (RPO) of this bucket. Set to ASYNC_TURBO to turn on Turbo Replication on a bucket.
pub rpo: Option<String>,
/// Reserved for future use.
#[serde(rename = "satisfiesPZI")]
pub satisfies_pzi: Option<bool>,
/// Reserved for future use.
#[serde(rename = "satisfiesPZS")]
pub satisfies_pzs: Option<bool>,
/// The URI of this bucket.
#[serde(rename = "selfLink")]
pub self_link: Option<String>,
/// The bucket's soft delete policy, which defines the period of time that soft-deleted objects will be retained, and cannot be permanently deleted.
#[serde(rename = "softDeletePolicy")]
pub soft_delete_policy: Option<BucketSoftDeletePolicy>,
/// The soft delete time of the bucket in RFC 3339 format.
#[serde(rename = "softDeleteTime")]
pub soft_delete_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The bucket's default storage class, used whenever no storageClass is specified for a newly-created object. This defines how objects in the bucket are stored and determines the SLA and the cost of storage. Values include MULTI_REGIONAL, REGIONAL, STANDARD, NEARLINE, COLDLINE, ARCHIVE, and DURABLE_REDUCED_AVAILABILITY. If this value is not specified when the bucket is created, it will default to STANDARD. For more information, see [Storage Classes](https://cloud.google.com/storage/docs/storage-classes).
#[serde(rename = "storageClass")]
pub storage_class: Option<String>,
/// The creation time of the bucket in RFC 3339 format.
#[serde(rename = "timeCreated")]
pub time_created: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The modification time of the bucket in RFC 3339 format.
pub updated: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The bucket's versioning configuration.
pub versioning: Option<BucketVersioning>,
/// The bucket's website configuration, controlling how the service behaves when accessing bucket contents as a web site. See the [Static Website Examples](https://cloud.google.com/storage/docs/static-website) for more information.
pub website: Option<BucketWebsite>,
}
impl common::RequestValue for Bucket {}
impl common::Resource for Bucket {}
impl common::ResponseResult for Bucket {}
/// An access-control entry.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [delete bucket access controls](BucketAccessControlDeleteCall) (none)
/// * [get bucket access controls](BucketAccessControlGetCall) (response)
/// * [insert bucket access controls](BucketAccessControlInsertCall) (request|response)
/// * [list bucket access controls](BucketAccessControlListCall) (none)
/// * [patch bucket access controls](BucketAccessControlPatchCall) (request|response)
/// * [update bucket access controls](BucketAccessControlUpdateCall) (request|response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketAccessControl {
/// The name of the bucket.
pub bucket: Option<String>,
/// The domain associated with the entity, if any.
pub domain: Option<String>,
/// The email address associated with the entity, if any.
pub email: Option<String>,
/// The entity holding the permission, in one of the following forms:
/// - user-userId
/// - user-email
/// - group-groupId
/// - group-email
/// - domain-domain
/// - project-team-projectId
/// - allUsers
/// - allAuthenticatedUsers Examples:
/// - The user liz@example.com would be user-liz@example.com.
/// - The group example@googlegroups.com would be group-example@googlegroups.com.
/// - To refer to all members of the Google Apps for Business domain example.com, the entity would be domain-example.com.
pub entity: Option<String>,
/// The ID for the entity, if any.
#[serde(rename = "entityId")]
pub entity_id: Option<String>,
/// HTTP 1.1 Entity tag for the access-control entry.
pub etag: Option<String>,
/// The ID of the access-control entry.
pub id: Option<String>,
/// The kind of item this is. For bucket access control entries, this is always storage#bucketAccessControl.
pub kind: Option<String>,
/// The project team associated with the entity, if any.
#[serde(rename = "projectTeam")]
pub project_team: Option<BucketAccessControlProjectTeam>,
/// The access permission for the entity.
pub role: Option<String>,
/// The link to this access-control entry.
#[serde(rename = "selfLink")]
pub self_link: Option<String>,
}
impl common::RequestValue for BucketAccessControl {}
impl common::Resource for BucketAccessControl {}
impl common::ResponseResult for BucketAccessControl {}
/// An access-control list.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [list bucket access controls](BucketAccessControlListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketAccessControls {
/// The list of items.
pub items: Option<Vec<BucketAccessControl>>,
/// The kind of item this is. For lists of bucket access control entries, this is always storage#bucketAccessControls.
pub kind: Option<String>,
}
impl common::ResponseResult for BucketAccessControls {}
/// The storage layout configuration of a bucket.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [get storage layout buckets](BucketGetStorageLayoutCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketStorageLayout {
/// The name of the bucket.
pub bucket: Option<String>,
/// The bucket's custom placement configuration for Custom Dual Regions.
#[serde(rename = "customPlacementConfig")]
pub custom_placement_config: Option<BucketStorageLayoutCustomPlacementConfig>,
/// The bucket's hierarchical namespace configuration.
#[serde(rename = "hierarchicalNamespace")]
pub hierarchical_namespace: Option<BucketStorageLayoutHierarchicalNamespace>,
/// The kind of item this is. For storage layout, this is always storage#storageLayout.
pub kind: Option<String>,
/// The location of the bucket.
pub location: Option<String>,
/// The type of the bucket location.
#[serde(rename = "locationType")]
pub location_type: Option<String>,
}
impl common::ResponseResult for BucketStorageLayout {}
/// A list of buckets.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [list buckets](BucketListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Buckets {
/// The list of items.
pub items: Option<Vec<Bucket>>,
/// The kind of item this is. For lists of buckets, this is always storage#buckets.
pub kind: Option<String>,
/// The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
/// The list of bucket resource names that could not be reached during the listing operation.
pub unreachable: Option<Vec<String>>,
}
impl common::ResponseResult for Buckets {}
/// A bulk restore objects request.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [bulk restore objects](ObjectBulkRestoreCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BulkRestoreObjectsRequest {
/// If false (default), the restore will not overwrite live objects with the same name at the destination. This means some deleted objects may be skipped. If true, live objects will be overwritten resulting in a noncurrent object (if versioning is enabled). If versioning is not enabled, overwriting the object will result in a soft-deleted object. In either case, if a noncurrent object already exists with the same name, a live version can be written without issue.
#[serde(rename = "allowOverwrite")]
pub allow_overwrite: Option<bool>,
/// If true, copies the source object's ACL; otherwise, uses the bucket's default object ACL. The default is false.
#[serde(rename = "copySourceAcl")]
pub copy_source_acl: Option<bool>,
/// Restores only the objects that were created after this time.
#[serde(rename = "createdAfterTime")]
pub created_after_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// Restores only the objects that were created before this time.
#[serde(rename = "createdBeforeTime")]
pub created_before_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// Restores only the objects matching any of the specified glob(s). If this parameter is not specified, all objects will be restored within the specified time range.
#[serde(rename = "matchGlobs")]
pub match_globs: Option<Vec<String>>,
/// Restores only the objects that were soft-deleted after this time.
#[serde(rename = "softDeletedAfterTime")]
pub soft_deleted_after_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// Restores only the objects that were soft-deleted before this time.
#[serde(rename = "softDeletedBeforeTime")]
pub soft_deleted_before_time: Option<chrono::DateTime<chrono::offset::Utc>>,
}
impl common::RequestValue for BulkRestoreObjectsRequest {}
/// An notification channel used to watch for resource changes.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [stop channels](ChannelStopCall) (request)
/// * [watch all objects](ObjectWatchAllCall) (request|response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Channel {
/// The address where notifications are delivered for this channel.
pub address: Option<String>,
/// Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional.
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub expiration: Option<i64>,
/// A UUID or similar unique string that identifies this channel.
pub id: Option<String>,
/// Identifies this as a notification channel used to watch for changes to a resource, which is "api#channel".
pub kind: Option<String>,
/// Additional parameters controlling delivery channel behavior. Optional.
pub params: Option<HashMap<String, String>>,
/// A Boolean value to indicate whether payload is wanted. Optional.
pub payload: Option<bool>,
/// An opaque ID that identifies the resource being watched on this channel. Stable across different API versions.
#[serde(rename = "resourceId")]
pub resource_id: Option<String>,
/// A version-specific identifier for the watched resource.
#[serde(rename = "resourceUri")]
pub resource_uri: Option<String>,
/// An arbitrary string delivered to the target address with each notification delivered over this channel. Optional.
pub token: Option<String>,
/// The type of delivery mechanism used for this channel.
#[serde(rename = "type")]
pub type_: Option<String>,
}
impl common::RequestValue for Channel {}
impl common::Resource for Channel {}
impl common::ResponseResult for Channel {}
/// A Compose request.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [compose objects](ObjectComposeCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ComposeRequest {
/// If true, the source objects will be deleted.
#[serde(rename = "deleteSourceObjects")]
pub delete_source_objects: Option<bool>,
/// Properties of the resulting object.
pub destination: Option<Object>,
/// The kind of item this is.
pub kind: Option<String>,
/// The list of source objects that will be concatenated into a single object.
#[serde(rename = "sourceObjects")]
pub source_objects: Option<Vec<ComposeRequestSourceObjects>>,
}
impl common::RequestValue for ComposeRequest {}
/// Represents an expression text. Example: title: "User account presence" description: "Determines whether the request has a user account" expression: "size(request.user) > 0"
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Expr {
/// An optional description of the expression. This is a longer text which describes the expression, e.g. when hovered over it in a UI.
pub description: Option<String>,
/// Textual representation of an expression in Common Expression Language syntax. The application context of the containing message determines which well-known feature set of CEL is supported.
pub expression: Option<String>,
/// An optional string indicating the location of the expression for error reporting, e.g. a file name and a position in the file.
pub location: Option<String>,
/// An optional title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs which allow to enter the expression.
pub title: Option<String>,
}
impl common::Part for Expr {}
/// A folder. Only available in buckets with hierarchical namespace enabled.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [delete folders](FolderDeleteCall) (none)
/// * [get folders](FolderGetCall) (response)
/// * [insert folders](FolderInsertCall) (request|response)
/// * [list folders](FolderListCall) (none)
/// * [rename folders](FolderRenameCall) (none)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Folder {
/// The name of the bucket containing this folder.
pub bucket: Option<String>,
/// The creation time of the folder in RFC 3339 format.
#[serde(rename = "createTime")]
pub create_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The ID of the folder, including the bucket name, folder name.
pub id: Option<String>,
/// The kind of item this is. For folders, this is always storage#folder.
pub kind: Option<String>,
/// The version of the metadata for this folder. Used for preconditions and for detecting changes in metadata.
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub metageneration: Option<i64>,
/// The name of the folder. Required if not specified by URL parameter.
pub name: Option<String>,
/// Only present if the folder is part of an ongoing rename folder operation. Contains information which can be used to query the operation status.
#[serde(rename = "pendingRenameInfo")]
pub pending_rename_info: Option<FolderPendingRenameInfo>,
/// The link to this folder.
#[serde(rename = "selfLink")]
pub self_link: Option<String>,
/// The modification time of the folder metadata in RFC 3339 format.
#[serde(rename = "updateTime")]
pub update_time: Option<chrono::DateTime<chrono::offset::Utc>>,
}
impl common::RequestValue for Folder {}
impl common::Resource for Folder {}
impl common::ResponseResult for Folder {}
/// A list of folders.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [list folders](FolderListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Folders {
/// The list of items.
pub items: Option<Vec<Folder>>,
/// The kind of item this is. For lists of folders, this is always storage#folders.
pub kind: Option<String>,
/// The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
}
impl common::ResponseResult for Folders {}
/// The response message for storage.buckets.operations.list.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [operations list buckets](BucketOperationListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct GoogleLongrunningListOperationsResponse {
/// The kind of item this is. For lists of operations, this is always storage#operations.
pub kind: Option<String>,
/// The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
/// A list of operations that matches the specified filter in the request.
pub operations: Option<Vec<GoogleLongrunningOperation>>,
}
impl common::ResponseResult for GoogleLongrunningListOperationsResponse {}
/// This resource represents a long-running operation that is the result of a network API call.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [insert anywhere caches](AnywhereCachInsertCall) (response)
/// * [update anywhere caches](AnywhereCachUpdateCall) (response)
/// * [relocate buckets](BucketRelocateCall) (response)
/// * [rename folders](FolderRenameCall) (response)
/// * [bulk restore objects](ObjectBulkRestoreCall) (response)
/// * [operations get buckets](BucketOperationGetCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct GoogleLongrunningOperation {
/// If the value is "false", it means the operation is still in progress. If "true", the operation is completed, and either "error" or "response" is available.
pub done: Option<bool>,
/// The error result of the operation in case of failure or cancellation.
pub error: Option<GoogleRpcStatus>,
/// The kind of item this is. For operations, this is always storage#operation.
pub kind: Option<String>,
/// Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
pub metadata: Option<HashMap<String, serde_json::Value>>,
/// The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the "name" should be a resource name ending with "operations/{operationId}".
pub name: Option<String>,
/// The normal response of the operation in case of success. If the original method returns no data on success, such as "Delete", the response is google.protobuf.Empty. If the original method is standard Get/Create/Update, the response should be the resource. For other methods, the response should have the type "XxxResponse", where "Xxx" is the original method name. For example, if the original method name is "TakeSnapshot()", the inferred response type is "TakeSnapshotResponse".
pub response: Option<HashMap<String, serde_json::Value>>,
/// The link to this long running operation.
#[serde(rename = "selfLink")]
pub self_link: Option<String>,
}
impl common::ResponseResult for GoogleLongrunningOperation {}
/// The "Status" type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each "Status" message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct GoogleRpcStatus {
/// The status code, which should be an enum value of google.rpc.Code.
pub code: Option<i32>,
/// A list of messages that carry the error details. There is a common set of message types for APIs to use.
pub details: Option<Vec<HashMap<String, serde_json::Value>>>,
/// A developer-facing error message, which should be in English.
pub message: Option<String>,
}
impl common::Part for GoogleRpcStatus {}
/// JSON template to produce a JSON-style HMAC Key resource for Create responses.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [hmac keys create projects](ProjectHmacKeyCreateCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct HmacKey {
/// The kind of item this is. For HMAC keys, this is always storage#hmacKey.
pub kind: Option<String>,
/// Key metadata.
pub metadata: Option<HmacKeyMetadata>,
/// HMAC secret key material.
pub secret: Option<String>,
}
impl common::ResponseResult for HmacKey {}
/// JSON template to produce a JSON-style HMAC Key metadata resource.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [hmac keys get projects](ProjectHmacKeyGetCall) (response)
/// * [hmac keys update projects](ProjectHmacKeyUpdateCall) (request|response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct HmacKeyMetadata {
/// The ID of the HMAC Key.
#[serde(rename = "accessId")]
pub access_id: Option<String>,
/// HTTP 1.1 Entity tag for the HMAC key.
pub etag: Option<String>,
/// The ID of the HMAC key, including the Project ID and the Access ID.
pub id: Option<String>,
/// The kind of item this is. For HMAC Key metadata, this is always storage#hmacKeyMetadata.
pub kind: Option<String>,
/// Project ID owning the service account to which the key authenticates.
#[serde(rename = "projectId")]
pub project_id: Option<String>,
/// The link to this resource.
#[serde(rename = "selfLink")]
pub self_link: Option<String>,
/// The email address of the key's associated service account.
#[serde(rename = "serviceAccountEmail")]
pub service_account_email: Option<String>,
/// The state of the key. Can be one of ACTIVE, INACTIVE, or DELETED.
pub state: Option<String>,
/// The creation time of the HMAC key in RFC 3339 format.
#[serde(rename = "timeCreated")]
pub time_created: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The last modification time of the HMAC key metadata in RFC 3339 format.
pub updated: Option<chrono::DateTime<chrono::offset::Utc>>,
}
impl common::RequestValue for HmacKeyMetadata {}
impl common::ResponseResult for HmacKeyMetadata {}
/// A list of hmacKeys.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [hmac keys list projects](ProjectHmacKeyListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct HmacKeysMetadata {
/// The list of items.
pub items: Option<Vec<HmacKeyMetadata>>,
/// The kind of item this is. For lists of hmacKeys, this is always storage#hmacKeysMetadata.
pub kind: Option<String>,
/// The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
}
impl common::ResponseResult for HmacKeysMetadata {}
/// A managed folder.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [delete managed folders](ManagedFolderDeleteCall) (none)
/// * [get managed folders](ManagedFolderGetCall) (response)
/// * [get iam policy managed folders](ManagedFolderGetIamPolicyCall) (none)
/// * [insert managed folders](ManagedFolderInsertCall) (request|response)
/// * [list managed folders](ManagedFolderListCall) (none)
/// * [set iam policy managed folders](ManagedFolderSetIamPolicyCall) (none)
/// * [test iam permissions managed folders](ManagedFolderTestIamPermissionCall) (none)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ManagedFolder {
/// The name of the bucket containing this managed folder.
pub bucket: Option<String>,
/// The creation time of the managed folder in RFC 3339 format.
#[serde(rename = "createTime")]
pub create_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The ID of the managed folder, including the bucket name and managed folder name.
pub id: Option<String>,
/// The kind of item this is. For managed folders, this is always storage#managedFolder.
pub kind: Option<String>,
/// The version of the metadata for this managed folder. Used for preconditions and for detecting changes in metadata.
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub metageneration: Option<i64>,
/// The name of the managed folder. Required if not specified by URL parameter.
pub name: Option<String>,
/// The link to this managed folder.
#[serde(rename = "selfLink")]
pub self_link: Option<String>,
/// The last update time of the managed folder metadata in RFC 3339 format.
#[serde(rename = "updateTime")]
pub update_time: Option<chrono::DateTime<chrono::offset::Utc>>,
}
impl common::RequestValue for ManagedFolder {}
impl common::Resource for ManagedFolder {}
impl common::ResponseResult for ManagedFolder {}
/// A list of managed folders.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [list managed folders](ManagedFolderListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ManagedFolders {
/// The list of items.
pub items: Option<Vec<ManagedFolder>>,
/// The kind of item this is. For lists of managed folders, this is always storage#managedFolders.
pub kind: Option<String>,
/// The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
}
impl common::ResponseResult for ManagedFolders {}
/// A subscription to receive Google PubSub notifications.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [delete notifications](NotificationDeleteCall) (none)
/// * [get notifications](NotificationGetCall) (response)
/// * [insert notifications](NotificationInsertCall) (request|response)
/// * [list notifications](NotificationListCall) (none)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Notification {
/// An optional list of additional attributes to attach to each Cloud PubSub message published for this notification subscription.
pub custom_attributes: Option<HashMap<String, String>>,
/// HTTP 1.1 Entity tag for this subscription notification.
pub etag: Option<String>,
/// If present, only send notifications about listed event types. If empty, sent notifications for all event types.
pub event_types: Option<Vec<String>>,
/// The ID of the notification.
pub id: Option<String>,
/// The kind of item this is. For notifications, this is always storage#notification.
pub kind: Option<String>,
/// If present, only apply this notification configuration to object names that begin with this prefix.
pub object_name_prefix: Option<String>,
/// The desired content of the Payload.
pub payload_format: Option<String>,
/// The canonical URL of this notification.
#[serde(rename = "selfLink")]
pub self_link: Option<String>,
/// The Cloud PubSub topic to which this subscription publishes. Formatted as: '//pubsub.googleapis.com/projects/{project-identifier}/topics/{my-topic}'
pub topic: Option<String>,
}
impl common::RequestValue for Notification {}
impl common::Resource for Notification {}
impl common::ResponseResult for Notification {}
/// A list of notification subscriptions.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [list notifications](NotificationListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Notifications {
/// The list of items.
pub items: Option<Vec<Notification>>,
/// The kind of item this is. For lists of notifications, this is always storage#notifications.
pub kind: Option<String>,
}
impl common::ResponseResult for Notifications {}
/// An object.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [bulk restore objects](ObjectBulkRestoreCall) (none)
/// * [compose objects](ObjectComposeCall) (response)
/// * [copy objects](ObjectCopyCall) (request|response)
/// * [delete objects](ObjectDeleteCall) (none)
/// * [get objects](ObjectGetCall) (response)
/// * [get iam policy objects](ObjectGetIamPolicyCall) (none)
/// * [insert objects](ObjectInsertCall) (request|response)
/// * [list objects](ObjectListCall) (none)
/// * [move objects](ObjectMoveCall) (response)
/// * [patch objects](ObjectPatchCall) (request|response)
/// * [restore objects](ObjectRestoreCall) (response)
/// * [rewrite objects](ObjectRewriteCall) (request)
/// * [set iam policy objects](ObjectSetIamPolicyCall) (none)
/// * [test iam permissions objects](ObjectTestIamPermissionCall) (none)
/// * [update objects](ObjectUpdateCall) (request|response)
/// * [watch all objects](ObjectWatchAllCall) (none)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Object {
/// Access controls on the object.
pub acl: Option<Vec<ObjectAccessControl>>,
/// The name of the bucket containing this object.
pub bucket: Option<String>,
/// Cache-Control directive for the object data. If omitted, and the object is accessible to all anonymous users, the default will be public, max-age=3600.
#[serde(rename = "cacheControl")]
pub cache_control: Option<String>,
/// Number of underlying components that make up this object. Components are accumulated by compose operations.
#[serde(rename = "componentCount")]
pub component_count: Option<i32>,
/// Content-Disposition of the object data.
#[serde(rename = "contentDisposition")]
pub content_disposition: Option<String>,
/// Content-Encoding of the object data.
#[serde(rename = "contentEncoding")]
pub content_encoding: Option<String>,
/// Content-Language of the object data.
#[serde(rename = "contentLanguage")]
pub content_language: Option<String>,
/// Content-Type of the object data. If an object is stored without a Content-Type, it is served as application/octet-stream.
#[serde(rename = "contentType")]
pub content_type: Option<String>,
/// User-defined or system-defined object contexts. Each object context is a key-payload pair, where the key provides the identification and the payload holds the associated value and additional metadata.
pub contexts: Option<ObjectContexts>,
/// CRC32c checksum, as described in RFC 4960, Appendix B; encoded using base64 in big-endian byte order. For more information about using the CRC32c checksum, see [Data Validation and Change Detection](https://cloud.google.com/storage/docs/data-validation).
pub crc32c: Option<String>,
/// A timestamp in RFC 3339 format specified by the user for an object.
#[serde(rename = "customTime")]
pub custom_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// Metadata of customer-supplied encryption key, if the object is encrypted by such a key.
#[serde(rename = "customerEncryption")]
pub customer_encryption: Option<ObjectCustomerEncryption>,
/// HTTP 1.1 Entity tag for the object.
pub etag: Option<String>,
/// Whether an object is under event-based hold. Event-based hold is a way to retain objects until an event occurs, which is signified by the hold's release (i.e. this value is set to false). After being released (set to false), such objects will be subject to bucket-level retention (if any). One sample use case of this flag is for banks to hold loan documents for at least 3 years after loan is paid in full. Here, bucket-level retention is 3 years and the event is the loan being paid in full. In this example, these objects will be held intact for any number of years until the event has occurred (event-based hold on the object is released) and then 3 more years after that. That means retention duration of the objects begins from the moment event-based hold transitioned from true to false.
#[serde(rename = "eventBasedHold")]
pub event_based_hold: Option<bool>,
/// The content generation of this object. Used for object versioning.
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub generation: Option<i64>,
/// This is the time (in the future) when the soft-deleted object will no longer be restorable. It is equal to the soft delete time plus the current soft delete retention duration of the bucket.
#[serde(rename = "hardDeleteTime")]
pub hard_delete_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The ID of the object, including the bucket name, object name, and generation number.
pub id: Option<String>,
/// The kind of item this is. For objects, this is always storage#object.
pub kind: Option<String>,
/// Not currently supported. Specifying the parameter causes the request to fail with status code 400 - Bad Request.
#[serde(rename = "kmsKeyName")]
pub kms_key_name: Option<String>,
/// MD5 hash of the data; encoded using base64. For more information about using the MD5 hash, see [Data Validation and Change Detection](https://cloud.google.com/storage/docs/data-validation).
#[serde(rename = "md5Hash")]
pub md5_hash: Option<String>,
/// Media download link.
#[serde(rename = "mediaLink")]
pub media_link: Option<String>,
/// User-provided metadata, in key/value pairs.
pub metadata: Option<HashMap<String, String>>,
/// The version of the metadata for this object at this generation. Used for preconditions and for detecting changes in metadata. A metageneration number is only meaningful in the context of a particular generation of a particular object.
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub metageneration: Option<i64>,
/// The name of the object. Required if not specified by URL parameter.
pub name: Option<String>,
/// The owner of the object. This will always be the uploader of the object.
pub owner: Option<ObjectOwner>,
/// Restore token used to differentiate deleted objects with the same name and generation. This field is only returned for deleted objects in hierarchical namespace buckets.
#[serde(rename = "restoreToken")]
pub restore_token: Option<String>,
/// A collection of object level retention parameters.
pub retention: Option<ObjectRetention>,
/// A server-determined value that specifies the earliest time that the object's retention period expires. This value is in RFC 3339 format. Note 1: This field is not provided for objects with an active event-based hold, since retention expiration is unknown until the hold is removed. Note 2: This value can be provided even when temporary hold is set (so that the user can reason about policy without having to first unset the temporary hold).
#[serde(rename = "retentionExpirationTime")]
pub retention_expiration_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The link to this object.
#[serde(rename = "selfLink")]
pub self_link: Option<String>,
/// Content-Length of the data in bytes.
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub size: Option<u64>,
/// The time at which the object became soft-deleted in RFC 3339 format.
#[serde(rename = "softDeleteTime")]
pub soft_delete_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// Storage class of the object.
#[serde(rename = "storageClass")]
pub storage_class: Option<String>,
/// Whether an object is under temporary hold. While this flag is set to true, the object is protected against deletion and overwrites. A common use case of this flag is regulatory investigations where objects need to be retained while the investigation is ongoing. Note that unlike event-based hold, temporary hold does not impact retention expiration time of an object.
#[serde(rename = "temporaryHold")]
pub temporary_hold: Option<bool>,
/// The creation time of the object in RFC 3339 format.
#[serde(rename = "timeCreated")]
pub time_created: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The time at which the object became noncurrent in RFC 3339 format. Will be returned if and only if this version of the object has been deleted.
#[serde(rename = "timeDeleted")]
pub time_deleted: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The time when the object was finalized.
#[serde(rename = "timeFinalized")]
pub time_finalized: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The time at which the object's storage class was last changed. When the object is initially created, it will be set to timeCreated.
#[serde(rename = "timeStorageClassUpdated")]
pub time_storage_class_updated: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The modification time of the object metadata in RFC 3339 format. Set initially to object creation time and then updated whenever any metadata of the object changes. This includes changes made by a requester, such as modifying custom metadata, as well as changes made by Cloud Storage on behalf of a requester, such as changing the storage class based on an Object Lifecycle Configuration.
pub updated: Option<chrono::DateTime<chrono::offset::Utc>>,
}
impl common::RequestValue for Object {}
impl common::Resource for Object {}
impl common::ResponseResult for Object {}
/// An access-control entry.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [get default object access controls](DefaultObjectAccessControlGetCall) (response)
/// * [insert default object access controls](DefaultObjectAccessControlInsertCall) (request|response)
/// * [patch default object access controls](DefaultObjectAccessControlPatchCall) (request|response)
/// * [update default object access controls](DefaultObjectAccessControlUpdateCall) (request|response)
/// * [delete object access controls](ObjectAccessControlDeleteCall) (none)
/// * [get object access controls](ObjectAccessControlGetCall) (response)
/// * [insert object access controls](ObjectAccessControlInsertCall) (request|response)
/// * [list object access controls](ObjectAccessControlListCall) (none)
/// * [patch object access controls](ObjectAccessControlPatchCall) (request|response)
/// * [update object access controls](ObjectAccessControlUpdateCall) (request|response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ObjectAccessControl {
/// The name of the bucket.
pub bucket: Option<String>,
/// The domain associated with the entity, if any.
pub domain: Option<String>,
/// The email address associated with the entity, if any.
pub email: Option<String>,
/// The entity holding the permission, in one of the following forms:
/// - user-userId
/// - user-email
/// - group-groupId
/// - group-email
/// - domain-domain
/// - project-team-projectId
/// - allUsers
/// - allAuthenticatedUsers Examples:
/// - The user liz@example.com would be user-liz@example.com.
/// - The group example@googlegroups.com would be group-example@googlegroups.com.
/// - To refer to all members of the Google Apps for Business domain example.com, the entity would be domain-example.com.
pub entity: Option<String>,
/// The ID for the entity, if any.
#[serde(rename = "entityId")]
pub entity_id: Option<String>,
/// HTTP 1.1 Entity tag for the access-control entry.
pub etag: Option<String>,
/// The content generation of the object, if applied to an object.
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub generation: Option<i64>,
/// The ID of the access-control entry.
pub id: Option<String>,
/// The kind of item this is. For object access control entries, this is always storage#objectAccessControl.
pub kind: Option<String>,
/// The name of the object, if applied to an object.
pub object: Option<String>,
/// The project team associated with the entity, if any.
#[serde(rename = "projectTeam")]
pub project_team: Option<ObjectAccessControlProjectTeam>,
/// The access permission for the entity.
pub role: Option<String>,
/// The link to this access-control entry.
#[serde(rename = "selfLink")]
pub self_link: Option<String>,
}
impl common::RequestValue for ObjectAccessControl {}
impl common::Resource for ObjectAccessControl {}
impl common::ResponseResult for ObjectAccessControl {}
/// An access-control list.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [list default object access controls](DefaultObjectAccessControlListCall) (response)
/// * [list object access controls](ObjectAccessControlListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ObjectAccessControls {
/// The list of items.
pub items: Option<Vec<ObjectAccessControl>>,
/// The kind of item this is. For lists of object access control entries, this is always storage#objectAccessControls.
pub kind: Option<String>,
}
impl common::ResponseResult for ObjectAccessControls {}
/// The payload of a single user-defined object context.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ObjectCustomContextPayload {
/// The time at which the object context was created in RFC 3339 format.
#[serde(rename = "createTime")]
pub create_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The time at which the object context was last updated in RFC 3339 format.
#[serde(rename = "updateTime")]
pub update_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The value of the object context.
pub value: Option<String>,
}
impl common::Part for ObjectCustomContextPayload {}
/// A list of objects.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [list objects](ObjectListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Objects {
/// The list of items.
pub items: Option<Vec<Object>>,
/// The kind of item this is. For lists of objects, this is always storage#objects.
pub kind: Option<String>,
/// The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
/// The list of prefixes of objects matching-but-not-listed up to and including the requested delimiter.
pub prefixes: Option<Vec<String>>,
}
impl common::ResponseResult for Objects {}
/// A bucket/object/managedFolder IAM policy.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [get iam policy buckets](BucketGetIamPolicyCall) (response)
/// * [set iam policy buckets](BucketSetIamPolicyCall) (request|response)
/// * [get iam policy managed folders](ManagedFolderGetIamPolicyCall) (response)
/// * [set iam policy managed folders](ManagedFolderSetIamPolicyCall) (request|response)
/// * [get iam policy objects](ObjectGetIamPolicyCall) (response)
/// * [set iam policy objects](ObjectSetIamPolicyCall) (request|response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Policy {
/// An association between a role, which comes with a set of permissions, and members who may assume that role.
pub bindings: Option<Vec<PolicyBindings>>,
/// HTTP 1.1 Entity tag for the policy.
#[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
pub etag: Option<Vec<u8>>,
/// The kind of item this is. For policies, this is always storage#policy. This field is ignored on input.
pub kind: Option<String>,
/// The ID of the resource to which this policy belongs. Will be of the form projects/_/buckets/bucket for buckets, projects/_/buckets/bucket/objects/object for objects, and projects/_/buckets/bucket/managedFolders/managedFolder. A specific generation may be specified by appending #generationNumber to the end of the object name, e.g. projects/_/buckets/my-bucket/objects/data.txt#17. The current generation can be denoted with #0. This field is ignored on input.
#[serde(rename = "resourceId")]
pub resource_id: Option<String>,
/// The IAM policy format version.
pub version: Option<i32>,
}
impl common::RequestValue for Policy {}
impl common::ResponseResult for Policy {}
/// A Relocate Bucket request.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [relocate buckets](BucketRelocateCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct RelocateBucketRequest {
/// The bucket's new custom placement configuration if relocating to a Custom Dual Region.
#[serde(rename = "destinationCustomPlacementConfig")]
pub destination_custom_placement_config:
Option<RelocateBucketRequestDestinationCustomPlacementConfig>,
/// The new location the bucket will be relocated to.
#[serde(rename = "destinationLocation")]
pub destination_location: Option<String>,
/// If true, validate the operation, but do not actually relocate the bucket.
#[serde(rename = "validateOnly")]
pub validate_only: Option<bool>,
}
impl common::RequestValue for RelocateBucketRequest {}
/// A rewrite response.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [rewrite objects](ObjectRewriteCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct RewriteResponse {
/// true if the copy is finished; otherwise, false if the copy is in progress. This property is always present in the response.
pub done: Option<bool>,
/// The kind of item this is.
pub kind: Option<String>,
/// The total size of the object being copied in bytes. This property is always present in the response.
#[serde(rename = "objectSize")]
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub object_size: Option<i64>,
/// A resource containing the metadata for the copied-to object. This property is present in the response only when copying completes.
pub resource: Option<Object>,
/// A token to use in subsequent requests to continue copying data. This token is present in the response only when there is more data to copy.
#[serde(rename = "rewriteToken")]
pub rewrite_token: Option<String>,
/// The total bytes written so far, which can be used to provide a waiting user with a progress indicator. This property is always present in the response.
#[serde(rename = "totalBytesRewritten")]
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub total_bytes_rewritten: Option<i64>,
}
impl common::ResponseResult for RewriteResponse {}
/// A subscription to receive Google PubSub notifications.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [service account get projects](ProjectServiceAccountGetCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ServiceAccount {
/// The ID of the notification.
pub email_address: Option<String>,
/// The kind of item this is. For notifications, this is always storage#notification.
pub kind: Option<String>,
}
impl common::ResponseResult for ServiceAccount {}
/// A storage.(buckets|objects|managedFolders).testIamPermissions response.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [test iam permissions buckets](BucketTestIamPermissionCall) (response)
/// * [test iam permissions managed folders](ManagedFolderTestIamPermissionCall) (response)
/// * [test iam permissions objects](ObjectTestIamPermissionCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct TestIamPermissionsResponse {
/// The kind of item this is.
pub kind: Option<String>,
/// The permissions held by the caller. Permissions are always of the format storage.resource.capability, where resource is one of buckets, objects, or managedFolders. The supported permissions are as follows:
/// - storage.buckets.delete - Delete bucket.
/// - storage.buckets.get - Read bucket metadata.
/// - storage.buckets.getIamPolicy - Read bucket IAM policy.
/// - storage.buckets.create - Create bucket.
/// - storage.buckets.list - List buckets.
/// - storage.buckets.setIamPolicy - Update bucket IAM policy.
/// - storage.buckets.update - Update bucket metadata.
/// - storage.objects.delete - Delete object.
/// - storage.objects.get - Read object data and metadata.
/// - storage.objects.getIamPolicy - Read object IAM policy.
/// - storage.objects.create - Create object.
/// - storage.objects.list - List objects.
/// - storage.objects.setIamPolicy - Update object IAM policy.
/// - storage.objects.update - Update object metadata.
/// - storage.managedFolders.delete - Delete managed folder.
/// - storage.managedFolders.get - Read managed folder metadata.
/// - storage.managedFolders.getIamPolicy - Read managed folder IAM policy.
/// - storage.managedFolders.create - Create managed folder.
/// - storage.managedFolders.list - List managed folders.
/// - storage.managedFolders.setIamPolicy - Update managed folder IAM policy.
pub permissions: Option<Vec<String>>,
}
impl common::ResponseResult for TestIamPermissionsResponse {}
/// The bucket's Autoclass configuration.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketAutoclass {
/// Whether or not Autoclass is enabled on this bucket
pub enabled: Option<bool>,
/// The storage class that objects in the bucket eventually transition to if they are not read for a certain length of time. Valid values are NEARLINE and ARCHIVE.
#[serde(rename = "terminalStorageClass")]
pub terminal_storage_class: Option<String>,
/// A date and time in RFC 3339 format representing the time of the most recent update to "terminalStorageClass".
#[serde(rename = "terminalStorageClassUpdateTime")]
pub terminal_storage_class_update_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// A date and time in RFC 3339 format representing the instant at which "enabled" was last toggled.
#[serde(rename = "toggleTime")]
pub toggle_time: Option<chrono::DateTime<chrono::offset::Utc>>,
}
impl common::NestedType for BucketAutoclass {}
impl common::Part for BucketAutoclass {}
/// The bucket's billing configuration.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketBilling {
/// When set to true, Requester Pays is enabled for this bucket.
#[serde(rename = "requesterPays")]
pub requester_pays: Option<bool>,
}
impl common::NestedType for BucketBilling {}
impl common::Part for BucketBilling {}
/// The bucket's Cross-Origin Resource Sharing (CORS) configuration.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketCors {
/// The value, in seconds, to return in the Access-Control-Max-Age header used in preflight responses.
#[serde(rename = "maxAgeSeconds")]
pub max_age_seconds: Option<i32>,
/// The list of HTTP methods on which to include CORS response headers, (GET, OPTIONS, POST, etc) Note: "*" is permitted in the list of methods, and means "any method".
pub method: Option<Vec<String>>,
/// The list of Origins eligible to receive CORS response headers. Note: "*" is permitted in the list of origins, and means "any Origin".
pub origin: Option<Vec<String>>,
/// The list of HTTP headers other than the simple response headers to give permission for the user-agent to share across domains.
#[serde(rename = "responseHeader")]
pub response_header: Option<Vec<String>>,
}
impl common::NestedType for BucketCors {}
impl common::Part for BucketCors {}
/// The bucket's custom placement configuration for Custom Dual Regions.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketCustomPlacementConfig {
/// The list of regional locations in which data is placed.
#[serde(rename = "dataLocations")]
pub data_locations: Option<Vec<String>>,
}
impl common::NestedType for BucketCustomPlacementConfig {}
impl common::Part for BucketCustomPlacementConfig {}
/// Encryption configuration for a bucket.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketEncryption {
/// If set, the new objects created in this bucket must comply with this enforcement config. Changing this has no effect on existing objects; it applies to new objects only. If omitted, the new objects are allowed to be encrypted with Customer Managed Encryption type by default.
#[serde(rename = "customerManagedEncryptionEnforcementConfig")]
pub customer_managed_encryption_enforcement_config:
Option<BucketEncryptionCustomerManagedEncryptionEnforcementConfig>,
/// If set, the new objects created in this bucket must comply with this enforcement config. Changing this has no effect on existing objects; it applies to new objects only. If omitted, the new objects are allowed to be encrypted with Customer Supplied Encryption type by default.
#[serde(rename = "customerSuppliedEncryptionEnforcementConfig")]
pub customer_supplied_encryption_enforcement_config:
Option<BucketEncryptionCustomerSuppliedEncryptionEnforcementConfig>,
/// A Cloud KMS key that will be used to encrypt objects inserted into this bucket, if no encryption method is specified.
#[serde(rename = "defaultKmsKeyName")]
pub default_kms_key_name: Option<String>,
/// If set, the new objects created in this bucket must comply with this enforcement config. Changing this has no effect on existing objects; it applies to new objects only. If omitted, the new objects are allowed to be encrypted with Google Managed Encryption type by default.
#[serde(rename = "googleManagedEncryptionEnforcementConfig")]
pub google_managed_encryption_enforcement_config:
Option<BucketEncryptionGoogleManagedEncryptionEnforcementConfig>,
}
impl common::NestedType for BucketEncryption {}
impl common::Part for BucketEncryption {}
/// If set, the new objects created in this bucket must comply with this enforcement config. Changing this has no effect on existing objects; it applies to new objects only. If omitted, the new objects are allowed to be encrypted with Customer Managed Encryption type by default.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketEncryptionCustomerManagedEncryptionEnforcementConfig {
/// Server-determined value that indicates the time from which configuration was enforced and effective. This value is in RFC 3339 format.
#[serde(rename = "effectiveTime")]
pub effective_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// Restriction mode for Customer-Managed Encryption Keys. Defaults to NotRestricted.
#[serde(rename = "restrictionMode")]
pub restriction_mode: Option<String>,
}
impl common::NestedType for BucketEncryptionCustomerManagedEncryptionEnforcementConfig {}
impl common::Part for BucketEncryptionCustomerManagedEncryptionEnforcementConfig {}
/// If set, the new objects created in this bucket must comply with this enforcement config. Changing this has no effect on existing objects; it applies to new objects only. If omitted, the new objects are allowed to be encrypted with Customer Supplied Encryption type by default.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketEncryptionCustomerSuppliedEncryptionEnforcementConfig {
/// Server-determined value that indicates the time from which configuration was enforced and effective. This value is in RFC 3339 format.
#[serde(rename = "effectiveTime")]
pub effective_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// Restriction mode for Customer-Supplied Encryption Keys. Defaults to NotRestricted.
#[serde(rename = "restrictionMode")]
pub restriction_mode: Option<String>,
}
impl common::NestedType for BucketEncryptionCustomerSuppliedEncryptionEnforcementConfig {}
impl common::Part for BucketEncryptionCustomerSuppliedEncryptionEnforcementConfig {}
/// If set, the new objects created in this bucket must comply with this enforcement config. Changing this has no effect on existing objects; it applies to new objects only. If omitted, the new objects are allowed to be encrypted with Google Managed Encryption type by default.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketEncryptionGoogleManagedEncryptionEnforcementConfig {
/// Server-determined value that indicates the time from which configuration was enforced and effective. This value is in RFC 3339 format.
#[serde(rename = "effectiveTime")]
pub effective_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// Restriction mode for Google-Managed Encryption Keys. Defaults to NotRestricted.
#[serde(rename = "restrictionMode")]
pub restriction_mode: Option<String>,
}
impl common::NestedType for BucketEncryptionGoogleManagedEncryptionEnforcementConfig {}
impl common::Part for BucketEncryptionGoogleManagedEncryptionEnforcementConfig {}
/// The bucket's hierarchical namespace configuration.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketHierarchicalNamespace {
/// When set to true, hierarchical namespace is enabled for this bucket.
pub enabled: Option<bool>,
}
impl common::NestedType for BucketHierarchicalNamespace {}
impl common::Part for BucketHierarchicalNamespace {}
/// The bucket's IAM configuration.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketIamConfiguration {
/// The bucket's uniform bucket-level access configuration. The feature was formerly known as Bucket Policy Only. For backward compatibility, this field will be populated with identical information as the uniformBucketLevelAccess field. We recommend using the uniformBucketLevelAccess field to enable and disable the feature.
#[serde(rename = "bucketPolicyOnly")]
pub bucket_policy_only: Option<BucketIamConfigurationBucketPolicyOnly>,
/// The bucket's Public Access Prevention configuration. Currently, 'inherited' and 'enforced' are supported.
#[serde(rename = "publicAccessPrevention")]
pub public_access_prevention: Option<String>,
/// The bucket's uniform bucket-level access configuration.
#[serde(rename = "uniformBucketLevelAccess")]
pub uniform_bucket_level_access: Option<BucketIamConfigurationUniformBucketLevelAccess>,
}
impl common::NestedType for BucketIamConfiguration {}
impl common::Part for BucketIamConfiguration {}
/// The bucket's uniform bucket-level access configuration. The feature was formerly known as Bucket Policy Only. For backward compatibility, this field will be populated with identical information as the uniformBucketLevelAccess field. We recommend using the uniformBucketLevelAccess field to enable and disable the feature.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketIamConfigurationBucketPolicyOnly {
/// If set, access is controlled only by bucket-level or above IAM policies.
pub enabled: Option<bool>,
/// The deadline for changing iamConfiguration.bucketPolicyOnly.enabled from true to false in RFC 3339 format. iamConfiguration.bucketPolicyOnly.enabled may be changed from true to false until the locked time, after which the field is immutable.
#[serde(rename = "lockedTime")]
pub locked_time: Option<chrono::DateTime<chrono::offset::Utc>>,
}
impl common::NestedType for BucketIamConfigurationBucketPolicyOnly {}
impl common::Part for BucketIamConfigurationBucketPolicyOnly {}
/// The bucket's uniform bucket-level access configuration.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketIamConfigurationUniformBucketLevelAccess {
/// If set, access is controlled only by bucket-level or above IAM policies.
pub enabled: Option<bool>,
/// The deadline for changing iamConfiguration.uniformBucketLevelAccess.enabled from true to false in RFC 3339 format. iamConfiguration.uniformBucketLevelAccess.enabled may be changed from true to false until the locked time, after which the field is immutable.
#[serde(rename = "lockedTime")]
pub locked_time: Option<chrono::DateTime<chrono::offset::Utc>>,
}
impl common::NestedType for BucketIamConfigurationUniformBucketLevelAccess {}
impl common::Part for BucketIamConfigurationUniformBucketLevelAccess {}
/// The bucket's IP filter configuration. Specifies the network sources that are allowed to access the operations on the bucket, as well as its underlying objects. Only enforced when the mode is set to 'Enabled'.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketIpFilter {
/// Whether to allow all service agents to access the bucket regardless of the IP filter configuration.
#[serde(rename = "allowAllServiceAgentAccess")]
pub allow_all_service_agent_access: Option<bool>,
/// Whether to allow cross-org VPCs in the bucket's IP filter configuration.
#[serde(rename = "allowCrossOrgVpcs")]
pub allow_cross_org_vpcs: Option<bool>,
/// The mode of the IP filter. Valid values are 'Enabled' and 'Disabled'.
pub mode: Option<String>,
/// The public network source of the bucket's IP filter.
#[serde(rename = "publicNetworkSource")]
pub public_network_source: Option<BucketIpFilterPublicNetworkSource>,
/// The list of [VPC network](https://cloud.google.com/vpc/docs/vpc) sources of the bucket's IP filter.
#[serde(rename = "vpcNetworkSources")]
pub vpc_network_sources: Option<Vec<BucketIpFilterVpcNetworkSources>>,
}
impl common::NestedType for BucketIpFilter {}
impl common::Part for BucketIpFilter {}
/// The public network source of the bucket's IP filter.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketIpFilterPublicNetworkSource {
/// The list of public IPv4, IPv6 cidr ranges that are allowed to access the bucket.
#[serde(rename = "allowedIpCidrRanges")]
pub allowed_ip_cidr_ranges: Option<Vec<String>>,
}
impl common::NestedType for BucketIpFilterPublicNetworkSource {}
impl common::Part for BucketIpFilterPublicNetworkSource {}
/// The list of [VPC network](https://cloud.google.com/vpc/docs/vpc) sources of the bucket's IP filter.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketIpFilterVpcNetworkSources {
/// The list of IPv4, IPv6 cidr ranges subnetworks that are allowed to access the bucket.
#[serde(rename = "allowedIpCidrRanges")]
pub allowed_ip_cidr_ranges: Option<Vec<String>>,
/// Name of the network. Format: projects/{PROJECT_ID}/global/networks/{NETWORK_NAME}
pub network: Option<String>,
}
impl common::NestedType for BucketIpFilterVpcNetworkSources {}
impl common::Part for BucketIpFilterVpcNetworkSources {}
/// The bucket's lifecycle configuration. See [Lifecycle Management](https://cloud.google.com/storage/docs/lifecycle) for more information.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketLifecycle {
/// A lifecycle management rule, which is made of an action to take and the condition(s) under which the action will be taken.
pub rule: Option<Vec<BucketLifecycleRule>>,
}
impl common::NestedType for BucketLifecycle {}
impl common::Part for BucketLifecycle {}
/// A lifecycle management rule, which is made of an action to take and the condition(s) under which the action will be taken.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketLifecycleRule {
/// The action to take.
pub action: Option<BucketLifecycleRuleAction>,
/// The condition(s) under which the action will be taken.
pub condition: Option<BucketLifecycleRuleCondition>,
}
impl common::NestedType for BucketLifecycleRule {}
impl common::Part for BucketLifecycleRule {}
/// The action to take.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketLifecycleRuleAction {
/// Target storage class. Required iff the type of the action is SetStorageClass.
#[serde(rename = "storageClass")]
pub storage_class: Option<String>,
/// Type of the action. Currently, only Delete, SetStorageClass, and AbortIncompleteMultipartUpload are supported.
#[serde(rename = "type")]
pub type_: Option<String>,
}
impl common::NestedType for BucketLifecycleRuleAction {}
impl common::Part for BucketLifecycleRuleAction {}
/// The condition(s) under which the action will be taken.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketLifecycleRuleCondition {
/// Age of an object (in days). This condition is satisfied when an object reaches the specified age.
pub age: Option<i32>,
/// A date in RFC 3339 format with only the date part (for instance, "2013-01-15"). This condition is satisfied when an object is created before midnight of the specified date in UTC.
#[serde(rename = "createdBefore")]
pub created_before: Option<chrono::NaiveDate>,
/// A date in RFC 3339 format with only the date part (for instance, "2013-01-15"). This condition is satisfied when the custom time on an object is before this date in UTC.
#[serde(rename = "customTimeBefore")]
pub custom_time_before: Option<chrono::NaiveDate>,
/// Number of days elapsed since the user-specified timestamp set on an object. The condition is satisfied if the days elapsed is at least this number. If no custom timestamp is specified on an object, the condition does not apply.
#[serde(rename = "daysSinceCustomTime")]
pub days_since_custom_time: Option<i32>,
/// Number of days elapsed since the noncurrent timestamp of an object. The condition is satisfied if the days elapsed is at least this number. This condition is relevant only for versioned objects. The value of the field must be a nonnegative integer. If it's zero, the object version will become eligible for Lifecycle action as soon as it becomes noncurrent.
#[serde(rename = "daysSinceNoncurrentTime")]
pub days_since_noncurrent_time: Option<i32>,
/// Relevant only for versioned objects. If the value is true, this condition matches live objects; if the value is false, it matches archived objects.
#[serde(rename = "isLive")]
pub is_live: Option<bool>,
/// A regular expression that satisfies the RE2 syntax. This condition is satisfied when the name of the object matches the RE2 pattern. Note: This feature is currently in the "Early Access" launch stage and is only available to a whitelisted set of users; that means that this feature may be changed in backward-incompatible ways and that it is not guaranteed to be released.
#[serde(rename = "matchesPattern")]
pub matches_pattern: Option<String>,
/// List of object name prefixes. This condition will be satisfied when at least one of the prefixes exactly matches the beginning of the object name.
#[serde(rename = "matchesPrefix")]
pub matches_prefix: Option<Vec<String>>,
/// Objects having any of the storage classes specified by this condition will be matched. Values include MULTI_REGIONAL, REGIONAL, NEARLINE, COLDLINE, ARCHIVE, STANDARD, and DURABLE_REDUCED_AVAILABILITY.
#[serde(rename = "matchesStorageClass")]
pub matches_storage_class: Option<Vec<String>>,
/// List of object name suffixes. This condition will be satisfied when at least one of the suffixes exactly matches the end of the object name.
#[serde(rename = "matchesSuffix")]
pub matches_suffix: Option<Vec<String>>,
/// A date in RFC 3339 format with only the date part (for instance, "2013-01-15"). This condition is satisfied when the noncurrent time on an object is before this date in UTC. This condition is relevant only for versioned objects.
#[serde(rename = "noncurrentTimeBefore")]
pub noncurrent_time_before: Option<chrono::NaiveDate>,
/// Relevant only for versioned objects. If the value is N, this condition is satisfied when there are at least N versions (including the live version) newer than this version of the object.
#[serde(rename = "numNewerVersions")]
pub num_newer_versions: Option<i32>,
}
impl common::NestedType for BucketLifecycleRuleCondition {}
impl common::Part for BucketLifecycleRuleCondition {}
/// The bucket's logging configuration, which defines the destination bucket and optional name prefix for the current bucket's logs.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketLogging {
/// The destination bucket where the current bucket's logs should be placed.
#[serde(rename = "logBucket")]
pub log_bucket: Option<String>,
/// A prefix for log object names.
#[serde(rename = "logObjectPrefix")]
pub log_object_prefix: Option<String>,
}
impl common::NestedType for BucketLogging {}
impl common::Part for BucketLogging {}
/// The bucket's object retention config.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketObjectRetention {
/// The bucket's object retention mode. Can be Enabled.
pub mode: Option<String>,
}
impl common::NestedType for BucketObjectRetention {}
impl common::Part for BucketObjectRetention {}
/// The owner of the bucket. This is always the project team's owner group.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketOwner {
/// The entity, in the form project-owner-projectId.
pub entity: Option<String>,
/// The ID for the entity.
#[serde(rename = "entityId")]
pub entity_id: Option<String>,
}
impl common::NestedType for BucketOwner {}
impl common::Part for BucketOwner {}
/// The bucket's retention policy. The retention policy enforces a minimum retention time for all objects contained in the bucket, based on their creation time. Any attempt to overwrite or delete objects younger than the retention period will result in a PERMISSION_DENIED error. An unlocked retention policy can be modified or removed from the bucket via a storage.buckets.update operation. A locked retention policy cannot be removed or shortened in duration for the lifetime of the bucket. Attempting to remove or decrease period of a locked retention policy will result in a PERMISSION_DENIED error.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketRetentionPolicy {
/// Server-determined value that indicates the time from which policy was enforced and effective. This value is in RFC 3339 format.
#[serde(rename = "effectiveTime")]
pub effective_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// Once locked, an object retention policy cannot be modified.
#[serde(rename = "isLocked")]
pub is_locked: Option<bool>,
/// The duration in seconds that objects need to be retained. Retention duration must be greater than zero and less than 100 years. Note that enforcement of retention periods less than a day is not guaranteed. Such periods should only be used for testing purposes.
#[serde(rename = "retentionPeriod")]
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub retention_period: Option<i64>,
}
impl common::NestedType for BucketRetentionPolicy {}
impl common::Part for BucketRetentionPolicy {}
/// The bucket's soft delete policy, which defines the period of time that soft-deleted objects will be retained, and cannot be permanently deleted.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketSoftDeletePolicy {
/// Server-determined value that indicates the time from which the policy, or one with a greater retention, was effective. This value is in RFC 3339 format.
#[serde(rename = "effectiveTime")]
pub effective_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The duration in seconds that soft-deleted objects in the bucket will be retained and cannot be permanently deleted.
#[serde(rename = "retentionDurationSeconds")]
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub retention_duration_seconds: Option<i64>,
}
impl common::NestedType for BucketSoftDeletePolicy {}
impl common::Part for BucketSoftDeletePolicy {}
/// The bucket's versioning configuration.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketVersioning {
/// While set to true, versioning is fully enabled for this bucket.
pub enabled: Option<bool>,
}
impl common::NestedType for BucketVersioning {}
impl common::Part for BucketVersioning {}
/// The bucket's website configuration, controlling how the service behaves when accessing bucket contents as a web site. See the [Static Website Examples](https://cloud.google.com/storage/docs/static-website) for more information.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketWebsite {
/// If the requested object path is missing, the service will ensure the path has a trailing '/', append this suffix, and attempt to retrieve the resulting object. This allows the creation of index.html objects to represent directory pages.
#[serde(rename = "mainPageSuffix")]
pub main_page_suffix: Option<String>,
/// If the requested object path is missing, and any mainPageSuffix object is missing, if applicable, the service will return the named object from this bucket as the content for a 404 Not Found result.
#[serde(rename = "notFoundPage")]
pub not_found_page: Option<String>,
}
impl common::NestedType for BucketWebsite {}
impl common::Part for BucketWebsite {}
/// The project team associated with the entity, if any.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketAccessControlProjectTeam {
/// The project number.
#[serde(rename = "projectNumber")]
pub project_number: Option<String>,
/// The team.
pub team: Option<String>,
}
impl common::NestedType for BucketAccessControlProjectTeam {}
impl common::Part for BucketAccessControlProjectTeam {}
/// The bucket's custom placement configuration for Custom Dual Regions.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketStorageLayoutCustomPlacementConfig {
/// The list of regional locations in which data is placed.
#[serde(rename = "dataLocations")]
pub data_locations: Option<Vec<String>>,
}
impl common::NestedType for BucketStorageLayoutCustomPlacementConfig {}
impl common::Part for BucketStorageLayoutCustomPlacementConfig {}
/// The bucket's hierarchical namespace configuration.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BucketStorageLayoutHierarchicalNamespace {
/// When set to true, hierarchical namespace is enabled for this bucket.
pub enabled: Option<bool>,
}
impl common::NestedType for BucketStorageLayoutHierarchicalNamespace {}
impl common::Part for BucketStorageLayoutHierarchicalNamespace {}
/// The list of source objects that will be concatenated into a single object.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ComposeRequestSourceObjects {
/// The generation of this object to use as the source.
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub generation: Option<i64>,
/// The source object's name. All source objects must reside in the same bucket.
pub name: Option<String>,
/// Conditions that must be met for this operation to execute.
#[serde(rename = "objectPreconditions")]
pub object_preconditions: Option<ComposeRequestSourceObjectsObjectPreconditions>,
}
impl common::NestedType for ComposeRequestSourceObjects {}
impl common::Part for ComposeRequestSourceObjects {}
/// Conditions that must be met for this operation to execute.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ComposeRequestSourceObjectsObjectPreconditions {
/// Only perform the composition if the generation of the source object that would be used matches this value. If this value and a generation are both specified, they must be the same value or the call will fail.
#[serde(rename = "ifGenerationMatch")]
#[serde_as(as = "Option<serde_with::DisplayFromStr>")]
pub if_generation_match: Option<i64>,
}
impl common::NestedType for ComposeRequestSourceObjectsObjectPreconditions {}
impl common::Part for ComposeRequestSourceObjectsObjectPreconditions {}
/// Only present if the folder is part of an ongoing rename folder operation. Contains information which can be used to query the operation status.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct FolderPendingRenameInfo {
/// The ID of the rename folder operation.
#[serde(rename = "operationId")]
pub operation_id: Option<String>,
}
impl common::NestedType for FolderPendingRenameInfo {}
impl common::Part for FolderPendingRenameInfo {}
/// User-defined or system-defined object contexts. Each object context is a key-payload pair, where the key provides the identification and the payload holds the associated value and additional metadata.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ObjectContexts {
/// User-defined object contexts.
pub custom: Option<HashMap<String, ObjectCustomContextPayload>>,
}
impl common::NestedType for ObjectContexts {}
impl common::Part for ObjectContexts {}
/// Metadata of customer-supplied encryption key, if the object is encrypted by such a key.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ObjectCustomerEncryption {
/// The encryption algorithm.
#[serde(rename = "encryptionAlgorithm")]
pub encryption_algorithm: Option<String>,
/// SHA256 hash value of the encryption key.
#[serde(rename = "keySha256")]
pub key_sha256: Option<String>,
}
impl common::NestedType for ObjectCustomerEncryption {}
impl common::Part for ObjectCustomerEncryption {}
/// The owner of the object. This will always be the uploader of the object.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ObjectOwner {
/// The entity, in the form user-userId.
pub entity: Option<String>,
/// The ID for the entity.
#[serde(rename = "entityId")]
pub entity_id: Option<String>,
}
impl common::NestedType for ObjectOwner {}
impl common::Part for ObjectOwner {}
/// A collection of object level retention parameters.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ObjectRetention {
/// The bucket's object retention mode, can only be Unlocked or Locked.
pub mode: Option<String>,
/// A time in RFC 3339 format until which object retention protects this object.
#[serde(rename = "retainUntilTime")]
pub retain_until_time: Option<chrono::DateTime<chrono::offset::Utc>>,
}
impl common::NestedType for ObjectRetention {}
impl common::Part for ObjectRetention {}
/// The project team associated with the entity, if any.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ObjectAccessControlProjectTeam {
/// The project number.
#[serde(rename = "projectNumber")]
pub project_number: Option<String>,
/// The team.
pub team: Option<String>,
}
impl common::NestedType for ObjectAccessControlProjectTeam {}
impl common::Part for ObjectAccessControlProjectTeam {}
/// An association between a role, which comes with a set of permissions, and members who may assume that role.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct PolicyBindings {
/// The condition that is associated with this binding. NOTE: an unsatisfied condition will not allow user access via current binding. Different bindings, including their conditions, are examined independently.
pub condition: Option<Expr>,
/// A collection of identifiers for members who may assume the provided role. Recognized identifiers are as follows:
/// - allUsers - A special identifier that represents anyone on the internet; with or without a Google account.
/// - allAuthenticatedUsers - A special identifier that represents anyone who is authenticated with a Google account or a service account.
/// - user:emailid - An email address that represents a specific account. For example, user:alice@gmail.com or user:joe@example.com.
/// - serviceAccount:emailid - An email address that represents a service account. For example, serviceAccount:my-other-app@appspot.gserviceaccount.com .
/// - group:emailid - An email address that represents a Google group. For example, group:admins@example.com.
/// - domain:domain - A Google Apps domain name that represents all the users of that domain. For example, domain:google.com or domain:example.com.
/// - projectOwner:projectid - Owners of the given project. For example, projectOwner:my-example-project
/// - projectEditor:projectid - Editors of the given project. For example, projectEditor:my-example-project
/// - projectViewer:projectid - Viewers of the given project. For example, projectViewer:my-example-project
pub members: Option<Vec<String>>,
/// The role to which members belong. Two types of roles are supported: new IAM roles, which grant permissions that do not map directly to those provided by ACLs, and legacy IAM roles, which do map directly to ACL permissions. All roles are of the format roles/storage.specificRole.
/// The new IAM roles are:
/// - roles/storage.admin - Full control of Google Cloud Storage resources.
/// - roles/storage.objectViewer - Read-Only access to Google Cloud Storage objects.
/// - roles/storage.objectCreator - Access to create objects in Google Cloud Storage.
/// - roles/storage.objectAdmin - Full control of Google Cloud Storage objects. The legacy IAM roles are:
/// - roles/storage.legacyObjectReader - Read-only access to objects without listing. Equivalent to an ACL entry on an object with the READER role.
/// - roles/storage.legacyObjectOwner - Read/write access to existing objects without listing. Equivalent to an ACL entry on an object with the OWNER role.
/// - roles/storage.legacyBucketReader - Read access to buckets with object listing. Equivalent to an ACL entry on a bucket with the READER role.
/// - roles/storage.legacyBucketWriter - Read access to buckets with object listing/creation/deletion. Equivalent to an ACL entry on a bucket with the WRITER role.
/// - roles/storage.legacyBucketOwner - Read and write access to existing buckets with object listing/creation/deletion. Equivalent to an ACL entry on a bucket with the OWNER role.
pub role: Option<String>,
}
impl common::NestedType for PolicyBindings {}
impl common::Part for PolicyBindings {}
/// The bucket's new custom placement configuration if relocating to a Custom Dual Region.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct RelocateBucketRequestDestinationCustomPlacementConfig {
/// The list of regional locations in which data is placed.
#[serde(rename = "dataLocations")]
pub data_locations: Option<Vec<String>>,
}
impl common::NestedType for RelocateBucketRequestDestinationCustomPlacementConfig {}
impl common::Part for RelocateBucketRequestDestinationCustomPlacementConfig {}
// ###################
// MethodBuilders ###
// #################
/// A builder providing access to all methods supported on *anywhereCach* resources.
/// It is not used directly, but through the [`Storage`] hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_storage1 as storage1;
///
/// # async fn dox() {
/// use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// let secret: yup_oauth2::ApplicationSecret = Default::default();
/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_only()
/// .enable_http2()
/// .build();
///
/// let executor = hyper_util::rt::TokioExecutor::new();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// yup_oauth2::client::CustomHyperClientBuilder::from(
/// hyper_util::client::legacy::Client::builder(executor).build(connector),
/// ),
/// ).build().await.unwrap();
///
/// let client = hyper_util::client::legacy::Client::builder(
/// hyper_util::rt::TokioExecutor::new()
/// )
/// .build(
/// hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_or_http()
/// .enable_http2()
/// .build()
/// );
/// let mut hub = Storage::new(client, auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `disable(...)`, `get(...)`, `insert(...)`, `list(...)`, `pause(...)`, `resume(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.anywhere_caches();
/// # }
/// ```
pub struct AnywhereCachMethods<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
}
impl<'a, C> common::MethodsBuilder for AnywhereCachMethods<'a, C> {}
impl<'a, C> AnywhereCachMethods<'a, C> {
/// Create a builder to help you perform the following task:
///
/// Disables an Anywhere Cache instance.
///
/// # Arguments
///
/// * `bucket` - Name of the parent bucket.
/// * `anywhereCacheId` - The ID of requested Anywhere Cache instance.
pub fn disable(&self, bucket: &str, anywhere_cache_id: &str) -> AnywhereCachDisableCall<'a, C> {
AnywhereCachDisableCall {
hub: self.hub,
_bucket: bucket.to_string(),
_anywhere_cache_id: anywhere_cache_id.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns the metadata of an Anywhere Cache instance.
///
/// # Arguments
///
/// * `bucket` - Name of the parent bucket.
/// * `anywhereCacheId` - The ID of requested Anywhere Cache instance.
pub fn get(&self, bucket: &str, anywhere_cache_id: &str) -> AnywhereCachGetCall<'a, C> {
AnywhereCachGetCall {
hub: self.hub,
_bucket: bucket.to_string(),
_anywhere_cache_id: anywhere_cache_id.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates an Anywhere Cache instance.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of the parent bucket.
pub fn insert(&self, request: AnywhereCache, bucket: &str) -> AnywhereCachInsertCall<'a, C> {
AnywhereCachInsertCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns a list of Anywhere Cache instances of the bucket matching the criteria.
///
/// # Arguments
///
/// * `bucket` - Name of the parent bucket.
pub fn list(&self, bucket: &str) -> AnywhereCachListCall<'a, C> {
AnywhereCachListCall {
hub: self.hub,
_bucket: bucket.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Pauses an Anywhere Cache instance.
///
/// # Arguments
///
/// * `bucket` - Name of the parent bucket.
/// * `anywhereCacheId` - The ID of requested Anywhere Cache instance.
pub fn pause(&self, bucket: &str, anywhere_cache_id: &str) -> AnywhereCachPauseCall<'a, C> {
AnywhereCachPauseCall {
hub: self.hub,
_bucket: bucket.to_string(),
_anywhere_cache_id: anywhere_cache_id.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Resumes a paused or disabled Anywhere Cache instance.
///
/// # Arguments
///
/// * `bucket` - Name of the parent bucket.
/// * `anywhereCacheId` - The ID of requested Anywhere Cache instance.
pub fn resume(&self, bucket: &str, anywhere_cache_id: &str) -> AnywhereCachResumeCall<'a, C> {
AnywhereCachResumeCall {
hub: self.hub,
_bucket: bucket.to_string(),
_anywhere_cache_id: anywhere_cache_id.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates the config(ttl and admissionPolicy) of an Anywhere Cache instance.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of the parent bucket.
/// * `anywhereCacheId` - The ID of requested Anywhere Cache instance.
pub fn update(
&self,
request: AnywhereCache,
bucket: &str,
anywhere_cache_id: &str,
) -> AnywhereCachUpdateCall<'a, C> {
AnywhereCachUpdateCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_anywhere_cache_id: anywhere_cache_id.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *bucketAccessControl* resources.
/// It is not used directly, but through the [`Storage`] hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_storage1 as storage1;
///
/// # async fn dox() {
/// use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// let secret: yup_oauth2::ApplicationSecret = Default::default();
/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_only()
/// .enable_http2()
/// .build();
///
/// let executor = hyper_util::rt::TokioExecutor::new();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// yup_oauth2::client::CustomHyperClientBuilder::from(
/// hyper_util::client::legacy::Client::builder(executor).build(connector),
/// ),
/// ).build().await.unwrap();
///
/// let client = hyper_util::client::legacy::Client::builder(
/// hyper_util::rt::TokioExecutor::new()
/// )
/// .build(
/// hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_or_http()
/// .enable_http2()
/// .build()
/// );
/// let mut hub = Storage::new(client, auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.bucket_access_controls();
/// # }
/// ```
pub struct BucketAccessControlMethods<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
}
impl<'a, C> common::MethodsBuilder for BucketAccessControlMethods<'a, C> {}
impl<'a, C> BucketAccessControlMethods<'a, C> {
/// Create a builder to help you perform the following task:
///
/// Permanently deletes the ACL entry for the specified entity on the specified bucket.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
/// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
pub fn delete(&self, bucket: &str, entity: &str) -> BucketAccessControlDeleteCall<'a, C> {
BucketAccessControlDeleteCall {
hub: self.hub,
_bucket: bucket.to_string(),
_entity: entity.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns the ACL entry for the specified entity on the specified bucket.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
/// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
pub fn get(&self, bucket: &str, entity: &str) -> BucketAccessControlGetCall<'a, C> {
BucketAccessControlGetCall {
hub: self.hub,
_bucket: bucket.to_string(),
_entity: entity.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a new ACL entry on the specified bucket.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of a bucket.
pub fn insert(
&self,
request: BucketAccessControl,
bucket: &str,
) -> BucketAccessControlInsertCall<'a, C> {
BucketAccessControlInsertCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Retrieves ACL entries on the specified bucket.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
pub fn list(&self, bucket: &str) -> BucketAccessControlListCall<'a, C> {
BucketAccessControlListCall {
hub: self.hub,
_bucket: bucket.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Patches an ACL entry on the specified bucket.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of a bucket.
/// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
pub fn patch(
&self,
request: BucketAccessControl,
bucket: &str,
entity: &str,
) -> BucketAccessControlPatchCall<'a, C> {
BucketAccessControlPatchCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_entity: entity.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates an ACL entry on the specified bucket.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of a bucket.
/// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
pub fn update(
&self,
request: BucketAccessControl,
bucket: &str,
entity: &str,
) -> BucketAccessControlUpdateCall<'a, C> {
BucketAccessControlUpdateCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_entity: entity.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *bucket* resources.
/// It is not used directly, but through the [`Storage`] hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_storage1 as storage1;
///
/// # async fn dox() {
/// use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// let secret: yup_oauth2::ApplicationSecret = Default::default();
/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_only()
/// .enable_http2()
/// .build();
///
/// let executor = hyper_util::rt::TokioExecutor::new();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// yup_oauth2::client::CustomHyperClientBuilder::from(
/// hyper_util::client::legacy::Client::builder(executor).build(connector),
/// ),
/// ).build().await.unwrap();
///
/// let client = hyper_util::client::legacy::Client::builder(
/// hyper_util::rt::TokioExecutor::new()
/// )
/// .build(
/// hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_or_http()
/// .enable_http2()
/// .build()
/// );
/// let mut hub = Storage::new(client, auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `get(...)`, `get_iam_policy(...)`, `get_storage_layout(...)`, `insert(...)`, `list(...)`, `lock_retention_policy(...)`, `operations_advance_relocate_bucket(...)`, `operations_cancel(...)`, `operations_get(...)`, `operations_list(...)`, `patch(...)`, `relocate(...)`, `restore(...)`, `set_iam_policy(...)`, `test_iam_permissions(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.buckets();
/// # }
/// ```
pub struct BucketMethods<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
}
impl<'a, C> common::MethodsBuilder for BucketMethods<'a, C> {}
impl<'a, C> BucketMethods<'a, C> {
/// Create a builder to help you perform the following task:
///
/// Deletes an empty bucket. Deletions are permanent unless soft delete is enabled on the bucket.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
pub fn delete(&self, bucket: &str) -> BucketDeleteCall<'a, C> {
BucketDeleteCall {
hub: self.hub,
_bucket: bucket.to_string(),
_user_project: Default::default(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns metadata for the specified bucket.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
pub fn get(&self, bucket: &str) -> BucketGetCall<'a, C> {
BucketGetCall {
hub: self.hub,
_bucket: bucket.to_string(),
_user_project: Default::default(),
_soft_deleted: Default::default(),
_projection: Default::default(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_generation: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns an IAM policy for the specified bucket.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
pub fn get_iam_policy(&self, bucket: &str) -> BucketGetIamPolicyCall<'a, C> {
BucketGetIamPolicyCall {
hub: self.hub,
_bucket: bucket.to_string(),
_user_project: Default::default(),
_options_requested_policy_version: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns the storage layout configuration for the specified bucket. Note that this operation requires storage.objects.list permission.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
pub fn get_storage_layout(&self, bucket: &str) -> BucketGetStorageLayoutCall<'a, C> {
BucketGetStorageLayoutCall {
hub: self.hub,
_bucket: bucket.to_string(),
_prefix: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a new bucket.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `project` - A valid API project identifier.
pub fn insert(&self, request: Bucket, project: &str) -> BucketInsertCall<'a, C> {
BucketInsertCall {
hub: self.hub,
_request: request,
_project: project.to_string(),
_user_project: Default::default(),
_projection: Default::default(),
_predefined_default_object_acl: Default::default(),
_predefined_acl: Default::default(),
_enable_object_retention: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Retrieves a list of buckets for a given project.
///
/// # Arguments
///
/// * `project` - A valid API project identifier.
pub fn list(&self, project: &str) -> BucketListCall<'a, C> {
BucketListCall {
hub: self.hub,
_project: project.to_string(),
_user_project: Default::default(),
_soft_deleted: Default::default(),
_return_partial_success: Default::default(),
_projection: Default::default(),
_prefix: Default::default(),
_page_token: Default::default(),
_max_results: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Locks retention policy on a bucket.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
/// * `ifMetagenerationMatch` - Makes the operation conditional on whether bucket's current metageneration matches the given value.
pub fn lock_retention_policy(
&self,
bucket: &str,
if_metageneration_match: i64,
) -> BucketLockRetentionPolicyCall<'a, C> {
BucketLockRetentionPolicyCall {
hub: self.hub,
_bucket: bucket.to_string(),
_if_metageneration_match: if_metageneration_match,
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Patches a bucket. Changes to the bucket will be readable immediately after writing, but configuration changes may take time to propagate.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of a bucket.
pub fn patch(&self, request: Bucket, bucket: &str) -> BucketPatchCall<'a, C> {
BucketPatchCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_user_project: Default::default(),
_projection: Default::default(),
_predefined_default_object_acl: Default::default(),
_predefined_acl: Default::default(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Initiates a long-running Relocate Bucket operation on the specified bucket.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of the bucket to be moved.
pub fn relocate(
&self,
request: RelocateBucketRequest,
bucket: &str,
) -> BucketRelocateCall<'a, C> {
BucketRelocateCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Restores a soft-deleted bucket.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
/// * `generation` - Generation of a bucket.
pub fn restore(&self, bucket: &str, generation: i64) -> BucketRestoreCall<'a, C> {
BucketRestoreCall {
hub: self.hub,
_bucket: bucket.to_string(),
_generation: generation,
_user_project: Default::default(),
_projection: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates an IAM policy for the specified bucket.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of a bucket.
pub fn set_iam_policy(&self, request: Policy, bucket: &str) -> BucketSetIamPolicyCall<'a, C> {
BucketSetIamPolicyCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Tests a set of permissions on the given bucket to see which, if any, are held by the caller.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
/// * `permissions` - Permissions to test.
pub fn test_iam_permissions(
&self,
bucket: &str,
permissions: &Vec<String>,
) -> BucketTestIamPermissionCall<'a, C> {
BucketTestIamPermissionCall {
hub: self.hub,
_bucket: bucket.to_string(),
_permissions: permissions.clone(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates a bucket. Changes to the bucket will be readable immediately after writing, but configuration changes may take time to propagate.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of a bucket.
pub fn update(&self, request: Bucket, bucket: &str) -> BucketUpdateCall<'a, C> {
BucketUpdateCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_user_project: Default::default(),
_projection: Default::default(),
_predefined_default_object_acl: Default::default(),
_predefined_acl: Default::default(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Starts asynchronous advancement of the relocate bucket operation in the case of required write downtime, to allow it to lock the bucket at the source location, and proceed with the bucket location swap. The server makes a best effort to advance the relocate bucket operation, but success is not guaranteed.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of the bucket to advance the relocate for.
/// * `operationId` - ID of the operation resource.
pub fn operations_advance_relocate_bucket(
&self,
request: AdvanceRelocateBucketOperationRequest,
bucket: &str,
operation_id: &str,
) -> BucketOperationAdvanceRelocateBucketCall<'a, C> {
BucketOperationAdvanceRelocateBucketCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_operation_id: operation_id.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed.
///
/// # Arguments
///
/// * `bucket` - The parent bucket of the operation resource.
/// * `operationId` - The ID of the operation resource.
pub fn operations_cancel(
&self,
bucket: &str,
operation_id: &str,
) -> BucketOperationCancelCall<'a, C> {
BucketOperationCancelCall {
hub: self.hub,
_bucket: bucket.to_string(),
_operation_id: operation_id.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Gets the latest state of a long-running operation.
///
/// # Arguments
///
/// * `bucket` - The parent bucket of the operation resource.
/// * `operationId` - The ID of the operation resource.
pub fn operations_get(
&self,
bucket: &str,
operation_id: &str,
) -> BucketOperationGetCall<'a, C> {
BucketOperationGetCall {
hub: self.hub,
_bucket: bucket.to_string(),
_operation_id: operation_id.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists operations that match the specified filter in the request.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket in which to look for operations.
pub fn operations_list(&self, bucket: &str) -> BucketOperationListCall<'a, C> {
BucketOperationListCall {
hub: self.hub,
_bucket: bucket.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_filter: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *channel* resources.
/// It is not used directly, but through the [`Storage`] hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_storage1 as storage1;
///
/// # async fn dox() {
/// use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// let secret: yup_oauth2::ApplicationSecret = Default::default();
/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_only()
/// .enable_http2()
/// .build();
///
/// let executor = hyper_util::rt::TokioExecutor::new();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// yup_oauth2::client::CustomHyperClientBuilder::from(
/// hyper_util::client::legacy::Client::builder(executor).build(connector),
/// ),
/// ).build().await.unwrap();
///
/// let client = hyper_util::client::legacy::Client::builder(
/// hyper_util::rt::TokioExecutor::new()
/// )
/// .build(
/// hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_or_http()
/// .enable_http2()
/// .build()
/// );
/// let mut hub = Storage::new(client, auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `stop(...)`
/// // to build up your call.
/// let rb = hub.channels();
/// # }
/// ```
pub struct ChannelMethods<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
}
impl<'a, C> common::MethodsBuilder for ChannelMethods<'a, C> {}
impl<'a, C> ChannelMethods<'a, C> {
/// Create a builder to help you perform the following task:
///
/// Stop watching resources through this channel
///
/// # Arguments
///
/// * `request` - No description provided.
pub fn stop(&self, request: Channel) -> ChannelStopCall<'a, C> {
ChannelStopCall {
hub: self.hub,
_request: request,
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *defaultObjectAccessControl* resources.
/// It is not used directly, but through the [`Storage`] hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_storage1 as storage1;
///
/// # async fn dox() {
/// use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// let secret: yup_oauth2::ApplicationSecret = Default::default();
/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_only()
/// .enable_http2()
/// .build();
///
/// let executor = hyper_util::rt::TokioExecutor::new();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// yup_oauth2::client::CustomHyperClientBuilder::from(
/// hyper_util::client::legacy::Client::builder(executor).build(connector),
/// ),
/// ).build().await.unwrap();
///
/// let client = hyper_util::client::legacy::Client::builder(
/// hyper_util::rt::TokioExecutor::new()
/// )
/// .build(
/// hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_or_http()
/// .enable_http2()
/// .build()
/// );
/// let mut hub = Storage::new(client, auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.default_object_access_controls();
/// # }
/// ```
pub struct DefaultObjectAccessControlMethods<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
}
impl<'a, C> common::MethodsBuilder for DefaultObjectAccessControlMethods<'a, C> {}
impl<'a, C> DefaultObjectAccessControlMethods<'a, C> {
/// Create a builder to help you perform the following task:
///
/// Permanently deletes the default object ACL entry for the specified entity on the specified bucket.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
/// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
pub fn delete(
&self,
bucket: &str,
entity: &str,
) -> DefaultObjectAccessControlDeleteCall<'a, C> {
DefaultObjectAccessControlDeleteCall {
hub: self.hub,
_bucket: bucket.to_string(),
_entity: entity.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns the default object ACL entry for the specified entity on the specified bucket.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
/// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
pub fn get(&self, bucket: &str, entity: &str) -> DefaultObjectAccessControlGetCall<'a, C> {
DefaultObjectAccessControlGetCall {
hub: self.hub,
_bucket: bucket.to_string(),
_entity: entity.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a new default object ACL entry on the specified bucket.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of a bucket.
pub fn insert(
&self,
request: ObjectAccessControl,
bucket: &str,
) -> DefaultObjectAccessControlInsertCall<'a, C> {
DefaultObjectAccessControlInsertCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Retrieves default object ACL entries on the specified bucket.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
pub fn list(&self, bucket: &str) -> DefaultObjectAccessControlListCall<'a, C> {
DefaultObjectAccessControlListCall {
hub: self.hub,
_bucket: bucket.to_string(),
_user_project: Default::default(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Patches a default object ACL entry on the specified bucket.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of a bucket.
/// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
pub fn patch(
&self,
request: ObjectAccessControl,
bucket: &str,
entity: &str,
) -> DefaultObjectAccessControlPatchCall<'a, C> {
DefaultObjectAccessControlPatchCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_entity: entity.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates a default object ACL entry on the specified bucket.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of a bucket.
/// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
pub fn update(
&self,
request: ObjectAccessControl,
bucket: &str,
entity: &str,
) -> DefaultObjectAccessControlUpdateCall<'a, C> {
DefaultObjectAccessControlUpdateCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_entity: entity.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *folder* resources.
/// It is not used directly, but through the [`Storage`] hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_storage1 as storage1;
///
/// # async fn dox() {
/// use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// let secret: yup_oauth2::ApplicationSecret = Default::default();
/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_only()
/// .enable_http2()
/// .build();
///
/// let executor = hyper_util::rt::TokioExecutor::new();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// yup_oauth2::client::CustomHyperClientBuilder::from(
/// hyper_util::client::legacy::Client::builder(executor).build(connector),
/// ),
/// ).build().await.unwrap();
///
/// let client = hyper_util::client::legacy::Client::builder(
/// hyper_util::rt::TokioExecutor::new()
/// )
/// .build(
/// hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_or_http()
/// .enable_http2()
/// .build()
/// );
/// let mut hub = Storage::new(client, auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)` and `rename(...)`
/// // to build up your call.
/// let rb = hub.folders();
/// # }
/// ```
pub struct FolderMethods<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
}
impl<'a, C> common::MethodsBuilder for FolderMethods<'a, C> {}
impl<'a, C> FolderMethods<'a, C> {
/// Create a builder to help you perform the following task:
///
/// Permanently deletes a folder. Only applicable to buckets with hierarchical namespace enabled.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket in which the folder resides.
/// * `folder` - Name of a folder.
pub fn delete(&self, bucket: &str, folder: &str) -> FolderDeleteCall<'a, C> {
FolderDeleteCall {
hub: self.hub,
_bucket: bucket.to_string(),
_folder: folder.to_string(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns metadata for the specified folder. Only applicable to buckets with hierarchical namespace enabled.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket in which the folder resides.
/// * `folder` - Name of a folder.
pub fn get(&self, bucket: &str, folder: &str) -> FolderGetCall<'a, C> {
FolderGetCall {
hub: self.hub,
_bucket: bucket.to_string(),
_folder: folder.to_string(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a new folder. Only applicable to buckets with hierarchical namespace enabled.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of the bucket in which the folder resides.
pub fn insert(&self, request: Folder, bucket: &str) -> FolderInsertCall<'a, C> {
FolderInsertCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_recursive: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Retrieves a list of folders matching the criteria. Only applicable to buckets with hierarchical namespace enabled.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket in which to look for folders.
pub fn list(&self, bucket: &str) -> FolderListCall<'a, C> {
FolderListCall {
hub: self.hub,
_bucket: bucket.to_string(),
_start_offset: Default::default(),
_prefix: Default::default(),
_page_token: Default::default(),
_page_size: Default::default(),
_end_offset: Default::default(),
_delimiter: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Renames a source folder to a destination folder. Only applicable to buckets with hierarchical namespace enabled.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket in which the folders are in.
/// * `sourceFolder` - Name of the source folder.
/// * `destinationFolder` - Name of the destination folder.
pub fn rename(
&self,
bucket: &str,
source_folder: &str,
destination_folder: &str,
) -> FolderRenameCall<'a, C> {
FolderRenameCall {
hub: self.hub,
_bucket: bucket.to_string(),
_source_folder: source_folder.to_string(),
_destination_folder: destination_folder.to_string(),
_if_source_metageneration_not_match: Default::default(),
_if_source_metageneration_match: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *managedFolder* resources.
/// It is not used directly, but through the [`Storage`] hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_storage1 as storage1;
///
/// # async fn dox() {
/// use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// let secret: yup_oauth2::ApplicationSecret = Default::default();
/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_only()
/// .enable_http2()
/// .build();
///
/// let executor = hyper_util::rt::TokioExecutor::new();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// yup_oauth2::client::CustomHyperClientBuilder::from(
/// hyper_util::client::legacy::Client::builder(executor).build(connector),
/// ),
/// ).build().await.unwrap();
///
/// let client = hyper_util::client::legacy::Client::builder(
/// hyper_util::rt::TokioExecutor::new()
/// )
/// .build(
/// hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_or_http()
/// .enable_http2()
/// .build()
/// );
/// let mut hub = Storage::new(client, auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `get(...)`, `get_iam_policy(...)`, `insert(...)`, `list(...)`, `set_iam_policy(...)` and `test_iam_permissions(...)`
/// // to build up your call.
/// let rb = hub.managed_folders();
/// # }
/// ```
pub struct ManagedFolderMethods<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
}
impl<'a, C> common::MethodsBuilder for ManagedFolderMethods<'a, C> {}
impl<'a, C> ManagedFolderMethods<'a, C> {
/// Create a builder to help you perform the following task:
///
/// Permanently deletes a managed folder.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket containing the managed folder.
/// * `managedFolder` - The managed folder name/path.
pub fn delete(&self, bucket: &str, managed_folder: &str) -> ManagedFolderDeleteCall<'a, C> {
ManagedFolderDeleteCall {
hub: self.hub,
_bucket: bucket.to_string(),
_managed_folder: managed_folder.to_string(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_allow_non_empty: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns metadata of the specified managed folder.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket containing the managed folder.
/// * `managedFolder` - The managed folder name/path.
pub fn get(&self, bucket: &str, managed_folder: &str) -> ManagedFolderGetCall<'a, C> {
ManagedFolderGetCall {
hub: self.hub,
_bucket: bucket.to_string(),
_managed_folder: managed_folder.to_string(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns an IAM policy for the specified managed folder.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket containing the managed folder.
/// * `managedFolder` - The managed folder name/path.
pub fn get_iam_policy(
&self,
bucket: &str,
managed_folder: &str,
) -> ManagedFolderGetIamPolicyCall<'a, C> {
ManagedFolderGetIamPolicyCall {
hub: self.hub,
_bucket: bucket.to_string(),
_managed_folder: managed_folder.to_string(),
_user_project: Default::default(),
_options_requested_policy_version: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a new managed folder.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of the bucket containing the managed folder.
pub fn insert(&self, request: ManagedFolder, bucket: &str) -> ManagedFolderInsertCall<'a, C> {
ManagedFolderInsertCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists managed folders in the given bucket.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket containing the managed folder.
pub fn list(&self, bucket: &str) -> ManagedFolderListCall<'a, C> {
ManagedFolderListCall {
hub: self.hub,
_bucket: bucket.to_string(),
_prefix: Default::default(),
_page_token: Default::default(),
_page_size: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates an IAM policy for the specified managed folder.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of the bucket containing the managed folder.
/// * `managedFolder` - The managed folder name/path.
pub fn set_iam_policy(
&self,
request: Policy,
bucket: &str,
managed_folder: &str,
) -> ManagedFolderSetIamPolicyCall<'a, C> {
ManagedFolderSetIamPolicyCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_managed_folder: managed_folder.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Tests a set of permissions on the given managed folder to see which, if any, are held by the caller.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket containing the managed folder.
/// * `managedFolder` - The managed folder name/path.
/// * `permissions` - Permissions to test.
pub fn test_iam_permissions(
&self,
bucket: &str,
managed_folder: &str,
permissions: &Vec<String>,
) -> ManagedFolderTestIamPermissionCall<'a, C> {
ManagedFolderTestIamPermissionCall {
hub: self.hub,
_bucket: bucket.to_string(),
_managed_folder: managed_folder.to_string(),
_permissions: permissions.clone(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *notification* resources.
/// It is not used directly, but through the [`Storage`] hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_storage1 as storage1;
///
/// # async fn dox() {
/// use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// let secret: yup_oauth2::ApplicationSecret = Default::default();
/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_only()
/// .enable_http2()
/// .build();
///
/// let executor = hyper_util::rt::TokioExecutor::new();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// yup_oauth2::client::CustomHyperClientBuilder::from(
/// hyper_util::client::legacy::Client::builder(executor).build(connector),
/// ),
/// ).build().await.unwrap();
///
/// let client = hyper_util::client::legacy::Client::builder(
/// hyper_util::rt::TokioExecutor::new()
/// )
/// .build(
/// hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_or_http()
/// .enable_http2()
/// .build()
/// );
/// let mut hub = Storage::new(client, auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `get(...)`, `insert(...)` and `list(...)`
/// // to build up your call.
/// let rb = hub.notifications();
/// # }
/// ```
pub struct NotificationMethods<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
}
impl<'a, C> common::MethodsBuilder for NotificationMethods<'a, C> {}
impl<'a, C> NotificationMethods<'a, C> {
/// Create a builder to help you perform the following task:
///
/// Permanently deletes a notification subscription.
///
/// # Arguments
///
/// * `bucket` - The parent bucket of the notification.
/// * `notification` - ID of the notification to delete.
pub fn delete(&self, bucket: &str, notification: &str) -> NotificationDeleteCall<'a, C> {
NotificationDeleteCall {
hub: self.hub,
_bucket: bucket.to_string(),
_notification: notification.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// View a notification configuration.
///
/// # Arguments
///
/// * `bucket` - The parent bucket of the notification.
/// * `notification` - Notification ID
pub fn get(&self, bucket: &str, notification: &str) -> NotificationGetCall<'a, C> {
NotificationGetCall {
hub: self.hub,
_bucket: bucket.to_string(),
_notification: notification.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a notification subscription for a given bucket.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - The parent bucket of the notification.
pub fn insert(&self, request: Notification, bucket: &str) -> NotificationInsertCall<'a, C> {
NotificationInsertCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Retrieves a list of notification subscriptions for a given bucket.
///
/// # Arguments
///
/// * `bucket` - Name of a Google Cloud Storage bucket.
pub fn list(&self, bucket: &str) -> NotificationListCall<'a, C> {
NotificationListCall {
hub: self.hub,
_bucket: bucket.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *objectAccessControl* resources.
/// It is not used directly, but through the [`Storage`] hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_storage1 as storage1;
///
/// # async fn dox() {
/// use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// let secret: yup_oauth2::ApplicationSecret = Default::default();
/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_only()
/// .enable_http2()
/// .build();
///
/// let executor = hyper_util::rt::TokioExecutor::new();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// yup_oauth2::client::CustomHyperClientBuilder::from(
/// hyper_util::client::legacy::Client::builder(executor).build(connector),
/// ),
/// ).build().await.unwrap();
///
/// let client = hyper_util::client::legacy::Client::builder(
/// hyper_util::rt::TokioExecutor::new()
/// )
/// .build(
/// hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_or_http()
/// .enable_http2()
/// .build()
/// );
/// let mut hub = Storage::new(client, auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)`
/// // to build up your call.
/// let rb = hub.object_access_controls();
/// # }
/// ```
pub struct ObjectAccessControlMethods<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
}
impl<'a, C> common::MethodsBuilder for ObjectAccessControlMethods<'a, C> {}
impl<'a, C> ObjectAccessControlMethods<'a, C> {
/// Create a builder to help you perform the following task:
///
/// Permanently deletes the ACL entry for the specified entity on the specified object.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
/// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
/// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
pub fn delete(
&self,
bucket: &str,
object: &str,
entity: &str,
) -> ObjectAccessControlDeleteCall<'a, C> {
ObjectAccessControlDeleteCall {
hub: self.hub,
_bucket: bucket.to_string(),
_object: object.to_string(),
_entity: entity.to_string(),
_user_project: Default::default(),
_generation: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns the ACL entry for the specified entity on the specified object.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
/// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
/// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
pub fn get(
&self,
bucket: &str,
object: &str,
entity: &str,
) -> ObjectAccessControlGetCall<'a, C> {
ObjectAccessControlGetCall {
hub: self.hub,
_bucket: bucket.to_string(),
_object: object.to_string(),
_entity: entity.to_string(),
_user_project: Default::default(),
_generation: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a new ACL entry on the specified object.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of a bucket.
/// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
pub fn insert(
&self,
request: ObjectAccessControl,
bucket: &str,
object: &str,
) -> ObjectAccessControlInsertCall<'a, C> {
ObjectAccessControlInsertCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_object: object.to_string(),
_user_project: Default::default(),
_generation: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Retrieves ACL entries on the specified object.
///
/// # Arguments
///
/// * `bucket` - Name of a bucket.
/// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
pub fn list(&self, bucket: &str, object: &str) -> ObjectAccessControlListCall<'a, C> {
ObjectAccessControlListCall {
hub: self.hub,
_bucket: bucket.to_string(),
_object: object.to_string(),
_user_project: Default::default(),
_generation: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Patches an ACL entry on the specified object.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of a bucket.
/// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
/// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
pub fn patch(
&self,
request: ObjectAccessControl,
bucket: &str,
object: &str,
entity: &str,
) -> ObjectAccessControlPatchCall<'a, C> {
ObjectAccessControlPatchCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_object: object.to_string(),
_entity: entity.to_string(),
_user_project: Default::default(),
_generation: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates an ACL entry on the specified object.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of a bucket.
/// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
/// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
pub fn update(
&self,
request: ObjectAccessControl,
bucket: &str,
object: &str,
entity: &str,
) -> ObjectAccessControlUpdateCall<'a, C> {
ObjectAccessControlUpdateCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_object: object.to_string(),
_entity: entity.to_string(),
_user_project: Default::default(),
_generation: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *object* resources.
/// It is not used directly, but through the [`Storage`] hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_storage1 as storage1;
///
/// # async fn dox() {
/// use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// let secret: yup_oauth2::ApplicationSecret = Default::default();
/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_only()
/// .enable_http2()
/// .build();
///
/// let executor = hyper_util::rt::TokioExecutor::new();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// yup_oauth2::client::CustomHyperClientBuilder::from(
/// hyper_util::client::legacy::Client::builder(executor).build(connector),
/// ),
/// ).build().await.unwrap();
///
/// let client = hyper_util::client::legacy::Client::builder(
/// hyper_util::rt::TokioExecutor::new()
/// )
/// .build(
/// hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_or_http()
/// .enable_http2()
/// .build()
/// );
/// let mut hub = Storage::new(client, auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `bulk_restore(...)`, `compose(...)`, `copy(...)`, `delete(...)`, `get(...)`, `get_iam_policy(...)`, `insert(...)`, `list(...)`, `move_(...)`, `patch(...)`, `restore(...)`, `rewrite(...)`, `set_iam_policy(...)`, `test_iam_permissions(...)`, `update(...)` and `watch_all(...)`
/// // to build up your call.
/// let rb = hub.objects();
/// # }
/// ```
pub struct ObjectMethods<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
}
impl<'a, C> common::MethodsBuilder for ObjectMethods<'a, C> {}
impl<'a, C> ObjectMethods<'a, C> {
/// Create a builder to help you perform the following task:
///
/// Initiates a long-running bulk restore operation on the specified bucket.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of the bucket in which the object resides.
pub fn bulk_restore(
&self,
request: BulkRestoreObjectsRequest,
bucket: &str,
) -> ObjectBulkRestoreCall<'a, C> {
ObjectBulkRestoreCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Concatenates a list of existing objects into a new object in the same bucket.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `destinationBucket` - Name of the bucket containing the source objects. The destination object is stored in this bucket.
/// * `destinationObject` - Name of the new object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
pub fn compose(
&self,
request: ComposeRequest,
destination_bucket: &str,
destination_object: &str,
) -> ObjectComposeCall<'a, C> {
ObjectComposeCall {
hub: self.hub,
_request: request,
_destination_bucket: destination_bucket.to_string(),
_destination_object: destination_object.to_string(),
_user_project: Default::default(),
_kms_key_name: Default::default(),
_if_metageneration_match: Default::default(),
_if_generation_match: Default::default(),
_destination_predefined_acl: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Copies a source object to a destination object. Optionally overrides metadata.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `sourceBucket` - Name of the bucket in which to find the source object.
/// * `sourceObject` - Name of the source object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
/// * `destinationBucket` - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
/// * `destinationObject` - Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any.
pub fn copy(
&self,
request: Object,
source_bucket: &str,
source_object: &str,
destination_bucket: &str,
destination_object: &str,
) -> ObjectCopyCall<'a, C> {
ObjectCopyCall {
hub: self.hub,
_request: request,
_source_bucket: source_bucket.to_string(),
_source_object: source_object.to_string(),
_destination_bucket: destination_bucket.to_string(),
_destination_object: destination_object.to_string(),
_user_project: Default::default(),
_source_generation: Default::default(),
_projection: Default::default(),
_if_source_metageneration_not_match: Default::default(),
_if_source_metageneration_match: Default::default(),
_if_source_generation_not_match: Default::default(),
_if_source_generation_match: Default::default(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_if_generation_not_match: Default::default(),
_if_generation_match: Default::default(),
_destination_predefined_acl: Default::default(),
_destination_kms_key_name: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Deletes an object and its metadata. Deletions are permanent if versioning is not enabled for the bucket, or if the generation parameter is used.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket in which the object resides.
/// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
pub fn delete(&self, bucket: &str, object: &str) -> ObjectDeleteCall<'a, C> {
ObjectDeleteCall {
hub: self.hub,
_bucket: bucket.to_string(),
_object: object.to_string(),
_user_project: Default::default(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_if_generation_not_match: Default::default(),
_if_generation_match: Default::default(),
_generation: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Retrieves an object or its metadata.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket in which the object resides.
/// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
pub fn get(&self, bucket: &str, object: &str) -> ObjectGetCall<'a, C> {
ObjectGetCall {
hub: self.hub,
_bucket: bucket.to_string(),
_object: object.to_string(),
_user_project: Default::default(),
_soft_deleted: Default::default(),
_restore_token: Default::default(),
_projection: Default::default(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_if_generation_not_match: Default::default(),
_if_generation_match: Default::default(),
_generation: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns an IAM policy for the specified object.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket in which the object resides.
/// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
pub fn get_iam_policy(&self, bucket: &str, object: &str) -> ObjectGetIamPolicyCall<'a, C> {
ObjectGetIamPolicyCall {
hub: self.hub,
_bucket: bucket.to_string(),
_object: object.to_string(),
_user_project: Default::default(),
_generation: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Stores a new object and metadata.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.
pub fn insert(&self, request: Object, bucket: &str) -> ObjectInsertCall<'a, C> {
ObjectInsertCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_user_project: Default::default(),
_projection: Default::default(),
_predefined_acl: Default::default(),
_name: Default::default(),
_kms_key_name: Default::default(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_if_generation_not_match: Default::default(),
_if_generation_match: Default::default(),
_content_encoding: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Retrieves a list of objects matching the criteria.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket in which to look for objects.
pub fn list(&self, bucket: &str) -> ObjectListCall<'a, C> {
ObjectListCall {
hub: self.hub,
_bucket: bucket.to_string(),
_versions: Default::default(),
_user_project: Default::default(),
_start_offset: Default::default(),
_soft_deleted: Default::default(),
_projection: Default::default(),
_prefix: Default::default(),
_page_token: Default::default(),
_max_results: Default::default(),
_match_glob: Default::default(),
_include_trailing_delimiter: Default::default(),
_include_folders_as_prefixes: Default::default(),
_filter: Default::default(),
_end_offset: Default::default(),
_delimiter: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Moves the source object to the destination object in the same bucket.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket in which the object resides.
/// * `sourceObject` - Name of the source object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
/// * `destinationObject` - Name of the destination object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
pub fn move_(
&self,
bucket: &str,
source_object: &str,
destination_object: &str,
) -> ObjectMoveCall<'a, C> {
ObjectMoveCall {
hub: self.hub,
_bucket: bucket.to_string(),
_source_object: source_object.to_string(),
_destination_object: destination_object.to_string(),
_user_project: Default::default(),
_projection: Default::default(),
_if_source_metageneration_not_match: Default::default(),
_if_source_metageneration_match: Default::default(),
_if_source_generation_not_match: Default::default(),
_if_source_generation_match: Default::default(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_if_generation_not_match: Default::default(),
_if_generation_match: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Patches an object's metadata.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of the bucket in which the object resides.
/// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
pub fn patch(&self, request: Object, bucket: &str, object: &str) -> ObjectPatchCall<'a, C> {
ObjectPatchCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_object: object.to_string(),
_user_project: Default::default(),
_projection: Default::default(),
_predefined_acl: Default::default(),
_override_unlocked_retention: Default::default(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_if_generation_not_match: Default::default(),
_if_generation_match: Default::default(),
_generation: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Restores a soft-deleted object.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket in which the object resides.
/// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
/// * `generation` - Selects a specific revision of this object.
pub fn restore(&self, bucket: &str, object: &str, generation: i64) -> ObjectRestoreCall<'a, C> {
ObjectRestoreCall {
hub: self.hub,
_bucket: bucket.to_string(),
_object: object.to_string(),
_generation: generation,
_user_project: Default::default(),
_restore_token: Default::default(),
_projection: Default::default(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_if_generation_not_match: Default::default(),
_if_generation_match: Default::default(),
_copy_source_acl: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Rewrites a source object to a destination object. Optionally overrides metadata.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `sourceBucket` - Name of the bucket in which to find the source object.
/// * `sourceObject` - Name of the source object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
/// * `destinationBucket` - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.
/// * `destinationObject` - Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
pub fn rewrite(
&self,
request: Object,
source_bucket: &str,
source_object: &str,
destination_bucket: &str,
destination_object: &str,
) -> ObjectRewriteCall<'a, C> {
ObjectRewriteCall {
hub: self.hub,
_request: request,
_source_bucket: source_bucket.to_string(),
_source_object: source_object.to_string(),
_destination_bucket: destination_bucket.to_string(),
_destination_object: destination_object.to_string(),
_user_project: Default::default(),
_source_generation: Default::default(),
_rewrite_token: Default::default(),
_projection: Default::default(),
_max_bytes_rewritten_per_call: Default::default(),
_if_source_metageneration_not_match: Default::default(),
_if_source_metageneration_match: Default::default(),
_if_source_generation_not_match: Default::default(),
_if_source_generation_match: Default::default(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_if_generation_not_match: Default::default(),
_if_generation_match: Default::default(),
_destination_predefined_acl: Default::default(),
_destination_kms_key_name: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates an IAM policy for the specified object.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of the bucket in which the object resides.
/// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
pub fn set_iam_policy(
&self,
request: Policy,
bucket: &str,
object: &str,
) -> ObjectSetIamPolicyCall<'a, C> {
ObjectSetIamPolicyCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_object: object.to_string(),
_user_project: Default::default(),
_generation: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Tests a set of permissions on the given object to see which, if any, are held by the caller.
///
/// # Arguments
///
/// * `bucket` - Name of the bucket in which the object resides.
/// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
/// * `permissions` - Permissions to test.
pub fn test_iam_permissions(
&self,
bucket: &str,
object: &str,
permissions: &Vec<String>,
) -> ObjectTestIamPermissionCall<'a, C> {
ObjectTestIamPermissionCall {
hub: self.hub,
_bucket: bucket.to_string(),
_object: object.to_string(),
_permissions: permissions.clone(),
_user_project: Default::default(),
_generation: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates an object's metadata.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of the bucket in which the object resides.
/// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
pub fn update(&self, request: Object, bucket: &str, object: &str) -> ObjectUpdateCall<'a, C> {
ObjectUpdateCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_object: object.to_string(),
_user_project: Default::default(),
_projection: Default::default(),
_predefined_acl: Default::default(),
_override_unlocked_retention: Default::default(),
_if_metageneration_not_match: Default::default(),
_if_metageneration_match: Default::default(),
_if_generation_not_match: Default::default(),
_if_generation_match: Default::default(),
_generation: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Watch for changes on all objects in a bucket.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `bucket` - Name of the bucket in which to look for objects.
pub fn watch_all(&self, request: Channel, bucket: &str) -> ObjectWatchAllCall<'a, C> {
ObjectWatchAllCall {
hub: self.hub,
_request: request,
_bucket: bucket.to_string(),
_versions: Default::default(),
_user_project: Default::default(),
_start_offset: Default::default(),
_projection: Default::default(),
_prefix: Default::default(),
_page_token: Default::default(),
_max_results: Default::default(),
_include_trailing_delimiter: Default::default(),
_end_offset: Default::default(),
_delimiter: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *project* resources.
/// It is not used directly, but through the [`Storage`] hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_storage1 as storage1;
///
/// # async fn dox() {
/// use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// let secret: yup_oauth2::ApplicationSecret = Default::default();
/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_only()
/// .enable_http2()
/// .build();
///
/// let executor = hyper_util::rt::TokioExecutor::new();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// yup_oauth2::client::CustomHyperClientBuilder::from(
/// hyper_util::client::legacy::Client::builder(executor).build(connector),
/// ),
/// ).build().await.unwrap();
///
/// let client = hyper_util::client::legacy::Client::builder(
/// hyper_util::rt::TokioExecutor::new()
/// )
/// .build(
/// hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_or_http()
/// .enable_http2()
/// .build()
/// );
/// let mut hub = Storage::new(client, auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `hmac_keys_create(...)`, `hmac_keys_delete(...)`, `hmac_keys_get(...)`, `hmac_keys_list(...)`, `hmac_keys_update(...)` and `service_account_get(...)`
/// // to build up your call.
/// let rb = hub.projects();
/// # }
/// ```
pub struct ProjectMethods<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
}
impl<'a, C> common::MethodsBuilder for ProjectMethods<'a, C> {}
impl<'a, C> ProjectMethods<'a, C> {
/// Create a builder to help you perform the following task:
///
/// Creates a new HMAC key for the specified service account.
///
/// # Arguments
///
/// * `projectId` - Project ID owning the service account.
/// * `serviceAccountEmail` - Email address of the service account.
pub fn hmac_keys_create(
&self,
project_id: &str,
service_account_email: &str,
) -> ProjectHmacKeyCreateCall<'a, C> {
ProjectHmacKeyCreateCall {
hub: self.hub,
_project_id: project_id.to_string(),
_service_account_email: service_account_email.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Deletes an HMAC key.
///
/// # Arguments
///
/// * `projectId` - Project ID owning the requested key
/// * `accessId` - Name of the HMAC key to be deleted.
pub fn hmac_keys_delete(
&self,
project_id: &str,
access_id: &str,
) -> ProjectHmacKeyDeleteCall<'a, C> {
ProjectHmacKeyDeleteCall {
hub: self.hub,
_project_id: project_id.to_string(),
_access_id: access_id.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Retrieves an HMAC key's metadata
///
/// # Arguments
///
/// * `projectId` - Project ID owning the service account of the requested key.
/// * `accessId` - Name of the HMAC key.
pub fn hmac_keys_get(&self, project_id: &str, access_id: &str) -> ProjectHmacKeyGetCall<'a, C> {
ProjectHmacKeyGetCall {
hub: self.hub,
_project_id: project_id.to_string(),
_access_id: access_id.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Retrieves a list of HMAC keys matching the criteria.
///
/// # Arguments
///
/// * `projectId` - Name of the project in which to look for HMAC keys.
pub fn hmac_keys_list(&self, project_id: &str) -> ProjectHmacKeyListCall<'a, C> {
ProjectHmacKeyListCall {
hub: self.hub,
_project_id: project_id.to_string(),
_user_project: Default::default(),
_show_deleted_keys: Default::default(),
_service_account_email: Default::default(),
_page_token: Default::default(),
_max_results: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates the state of an HMAC key. See the [HMAC Key resource descriptor](https://cloud.google.com/storage/docs/json_api/v1/projects/hmacKeys/update#request-body) for valid states.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `projectId` - Project ID owning the service account of the updated key.
/// * `accessId` - Name of the HMAC key being updated.
pub fn hmac_keys_update(
&self,
request: HmacKeyMetadata,
project_id: &str,
access_id: &str,
) -> ProjectHmacKeyUpdateCall<'a, C> {
ProjectHmacKeyUpdateCall {
hub: self.hub,
_request: request,
_project_id: project_id.to_string(),
_access_id: access_id.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Get the email address of this project's Google Cloud Storage service account.
///
/// # Arguments
///
/// * `projectId` - Project ID
pub fn service_account_get(&self, project_id: &str) -> ProjectServiceAccountGetCall<'a, C> {
ProjectServiceAccountGetCall {
hub: self.hub,
_project_id: project_id.to_string(),
_user_project: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
// ###################
// CallBuilders ###
// #################
/// Disables an Anywhere Cache instance.
///
/// A builder for the *disable* method supported by a *anywhereCach* resource.
/// It is not used directly, but through a [`AnywhereCachMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.anywhere_caches().disable("bucket", "anywhereCacheId")
/// .doit().await;
/// # }
/// ```
pub struct AnywhereCachDisableCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_anywhere_cache_id: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for AnywhereCachDisableCall<'a, C> {}
impl<'a, C> AnywhereCachDisableCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, AnywhereCache)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.anywhereCaches.disable",
http_method: hyper::Method::POST,
});
for &field in ["alt", "bucket", "anywhereCacheId"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("anywhereCacheId", self._anywhere_cache_id);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url =
self.hub._base_url.clone() + "b/{bucket}/anywhereCaches/{anywhereCacheId}/disable";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [
("{bucket}", "bucket"),
("{anywhereCacheId}", "anywhereCacheId"),
]
.iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["anywhereCacheId", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the parent bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> AnywhereCachDisableCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The ID of requested Anywhere Cache instance.
///
/// Sets the *anywhere cache id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn anywhere_cache_id(mut self, new_value: &str) -> AnywhereCachDisableCall<'a, C> {
self._anywhere_cache_id = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> AnywhereCachDisableCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> AnywhereCachDisableCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> AnywhereCachDisableCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> AnywhereCachDisableCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> AnywhereCachDisableCall<'a, C> {
self._scopes.clear();
self
}
}
/// Returns the metadata of an Anywhere Cache instance.
///
/// A builder for the *get* method supported by a *anywhereCach* resource.
/// It is not used directly, but through a [`AnywhereCachMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.anywhere_caches().get("bucket", "anywhereCacheId")
/// .doit().await;
/// # }
/// ```
pub struct AnywhereCachGetCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_anywhere_cache_id: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for AnywhereCachGetCall<'a, C> {}
impl<'a, C> AnywhereCachGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, AnywhereCache)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.anywhereCaches.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "bucket", "anywhereCacheId"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("anywhereCacheId", self._anywhere_cache_id);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/anywhereCaches/{anywhereCacheId}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [
("{bucket}", "bucket"),
("{anywhereCacheId}", "anywhereCacheId"),
]
.iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["anywhereCacheId", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the parent bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> AnywhereCachGetCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The ID of requested Anywhere Cache instance.
///
/// Sets the *anywhere cache id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn anywhere_cache_id(mut self, new_value: &str) -> AnywhereCachGetCall<'a, C> {
self._anywhere_cache_id = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> AnywhereCachGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> AnywhereCachGetCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> AnywhereCachGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> AnywhereCachGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> AnywhereCachGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Creates an Anywhere Cache instance.
///
/// A builder for the *insert* method supported by a *anywhereCach* resource.
/// It is not used directly, but through a [`AnywhereCachMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::AnywhereCache;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = AnywhereCache::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.anywhere_caches().insert(req, "bucket")
/// .doit().await;
/// # }
/// ```
pub struct AnywhereCachInsertCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: AnywhereCache,
_bucket: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for AnywhereCachInsertCall<'a, C> {}
impl<'a, C> AnywhereCachInsertCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, GoogleLongrunningOperation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.anywhereCaches.insert",
http_method: hyper::Method::POST,
});
for &field in ["alt", "bucket"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/anywhereCaches";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: AnywhereCache) -> AnywhereCachInsertCall<'a, C> {
self._request = new_value;
self
}
/// Name of the parent bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> AnywhereCachInsertCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> AnywhereCachInsertCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> AnywhereCachInsertCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> AnywhereCachInsertCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> AnywhereCachInsertCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> AnywhereCachInsertCall<'a, C> {
self._scopes.clear();
self
}
}
/// Returns a list of Anywhere Cache instances of the bucket matching the criteria.
///
/// A builder for the *list* method supported by a *anywhereCach* resource.
/// It is not used directly, but through a [`AnywhereCachMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.anywhere_caches().list("bucket")
/// .page_token("Lorem")
/// .page_size(-25)
/// .doit().await;
/// # }
/// ```
pub struct AnywhereCachListCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for AnywhereCachListCall<'a, C> {}
impl<'a, C> AnywhereCachListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, AnywhereCaches)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.anywhereCaches.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "bucket", "pageToken", "pageSize"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/anywhereCaches";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the parent bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> AnywhereCachListCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// A previously-returned page token representing part of the larger set of results to view.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> AnywhereCachListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Maximum number of items to return in a single page of responses. Maximum 1000.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> AnywhereCachListCall<'a, C> {
self._page_size = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> AnywhereCachListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> AnywhereCachListCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> AnywhereCachListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> AnywhereCachListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> AnywhereCachListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Pauses an Anywhere Cache instance.
///
/// A builder for the *pause* method supported by a *anywhereCach* resource.
/// It is not used directly, but through a [`AnywhereCachMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.anywhere_caches().pause("bucket", "anywhereCacheId")
/// .doit().await;
/// # }
/// ```
pub struct AnywhereCachPauseCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_anywhere_cache_id: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for AnywhereCachPauseCall<'a, C> {}
impl<'a, C> AnywhereCachPauseCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, AnywhereCache)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.anywhereCaches.pause",
http_method: hyper::Method::POST,
});
for &field in ["alt", "bucket", "anywhereCacheId"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("anywhereCacheId", self._anywhere_cache_id);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url =
self.hub._base_url.clone() + "b/{bucket}/anywhereCaches/{anywhereCacheId}/pause";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [
("{bucket}", "bucket"),
("{anywhereCacheId}", "anywhereCacheId"),
]
.iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["anywhereCacheId", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the parent bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> AnywhereCachPauseCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The ID of requested Anywhere Cache instance.
///
/// Sets the *anywhere cache id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn anywhere_cache_id(mut self, new_value: &str) -> AnywhereCachPauseCall<'a, C> {
self._anywhere_cache_id = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> AnywhereCachPauseCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> AnywhereCachPauseCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> AnywhereCachPauseCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> AnywhereCachPauseCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> AnywhereCachPauseCall<'a, C> {
self._scopes.clear();
self
}
}
/// Resumes a paused or disabled Anywhere Cache instance.
///
/// A builder for the *resume* method supported by a *anywhereCach* resource.
/// It is not used directly, but through a [`AnywhereCachMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.anywhere_caches().resume("bucket", "anywhereCacheId")
/// .doit().await;
/// # }
/// ```
pub struct AnywhereCachResumeCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_anywhere_cache_id: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for AnywhereCachResumeCall<'a, C> {}
impl<'a, C> AnywhereCachResumeCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, AnywhereCache)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.anywhereCaches.resume",
http_method: hyper::Method::POST,
});
for &field in ["alt", "bucket", "anywhereCacheId"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("anywhereCacheId", self._anywhere_cache_id);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url =
self.hub._base_url.clone() + "b/{bucket}/anywhereCaches/{anywhereCacheId}/resume";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [
("{bucket}", "bucket"),
("{anywhereCacheId}", "anywhereCacheId"),
]
.iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["anywhereCacheId", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the parent bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> AnywhereCachResumeCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The ID of requested Anywhere Cache instance.
///
/// Sets the *anywhere cache id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn anywhere_cache_id(mut self, new_value: &str) -> AnywhereCachResumeCall<'a, C> {
self._anywhere_cache_id = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> AnywhereCachResumeCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> AnywhereCachResumeCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> AnywhereCachResumeCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> AnywhereCachResumeCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> AnywhereCachResumeCall<'a, C> {
self._scopes.clear();
self
}
}
/// Updates the config(ttl and admissionPolicy) of an Anywhere Cache instance.
///
/// A builder for the *update* method supported by a *anywhereCach* resource.
/// It is not used directly, but through a [`AnywhereCachMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::AnywhereCache;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = AnywhereCache::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.anywhere_caches().update(req, "bucket", "anywhereCacheId")
/// .doit().await;
/// # }
/// ```
pub struct AnywhereCachUpdateCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: AnywhereCache,
_bucket: String,
_anywhere_cache_id: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for AnywhereCachUpdateCall<'a, C> {}
impl<'a, C> AnywhereCachUpdateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, GoogleLongrunningOperation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.anywhereCaches.update",
http_method: hyper::Method::PATCH,
});
for &field in ["alt", "bucket", "anywhereCacheId"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("anywhereCacheId", self._anywhere_cache_id);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/anywhereCaches/{anywhereCacheId}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [
("{bucket}", "bucket"),
("{anywhereCacheId}", "anywhereCacheId"),
]
.iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["anywhereCacheId", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PATCH)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: AnywhereCache) -> AnywhereCachUpdateCall<'a, C> {
self._request = new_value;
self
}
/// Name of the parent bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> AnywhereCachUpdateCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The ID of requested Anywhere Cache instance.
///
/// Sets the *anywhere cache id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn anywhere_cache_id(mut self, new_value: &str) -> AnywhereCachUpdateCall<'a, C> {
self._anywhere_cache_id = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> AnywhereCachUpdateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> AnywhereCachUpdateCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> AnywhereCachUpdateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> AnywhereCachUpdateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> AnywhereCachUpdateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Permanently deletes the ACL entry for the specified entity on the specified bucket.
///
/// A builder for the *delete* method supported by a *bucketAccessControl* resource.
/// It is not used directly, but through a [`BucketAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.bucket_access_controls().delete("bucket", "entity")
/// .user_project("sed")
/// .doit().await;
/// # }
/// ```
pub struct BucketAccessControlDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_entity: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketAccessControlDeleteCall<'a, C> {}
impl<'a, C> BucketAccessControlDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<common::Response> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.bucketAccessControls.delete",
http_method: hyper::Method::DELETE,
});
for &field in ["bucket", "entity", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("entity", self._entity);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
let mut url = self.hub._base_url.clone() + "b/{bucket}/acl/{entity}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{entity}", "entity")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["entity", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = common::Response::from_parts(parts, body);
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketAccessControlDeleteCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
///
/// Sets the *entity* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn entity(mut self, new_value: &str) -> BucketAccessControlDeleteCall<'a, C> {
self._entity = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketAccessControlDeleteCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketAccessControlDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketAccessControlDeleteCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketAccessControlDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketAccessControlDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketAccessControlDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Returns the ACL entry for the specified entity on the specified bucket.
///
/// A builder for the *get* method supported by a *bucketAccessControl* resource.
/// It is not used directly, but through a [`BucketAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.bucket_access_controls().get("bucket", "entity")
/// .user_project("vero")
/// .doit().await;
/// # }
/// ```
pub struct BucketAccessControlGetCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_entity: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketAccessControlGetCall<'a, C> {}
impl<'a, C> BucketAccessControlGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, BucketAccessControl)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.bucketAccessControls.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "bucket", "entity", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("entity", self._entity);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/acl/{entity}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{entity}", "entity")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["entity", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketAccessControlGetCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
///
/// Sets the *entity* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn entity(mut self, new_value: &str) -> BucketAccessControlGetCall<'a, C> {
self._entity = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketAccessControlGetCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketAccessControlGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketAccessControlGetCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketAccessControlGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketAccessControlGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketAccessControlGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Creates a new ACL entry on the specified bucket.
///
/// A builder for the *insert* method supported by a *bucketAccessControl* resource.
/// It is not used directly, but through a [`BucketAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::BucketAccessControl;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = BucketAccessControl::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.bucket_access_controls().insert(req, "bucket")
/// .user_project("sed")
/// .doit().await;
/// # }
/// ```
pub struct BucketAccessControlInsertCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: BucketAccessControl,
_bucket: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketAccessControlInsertCall<'a, C> {}
impl<'a, C> BucketAccessControlInsertCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, BucketAccessControl)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.bucketAccessControls.insert",
http_method: hyper::Method::POST,
});
for &field in ["alt", "bucket", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/acl";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: BucketAccessControl,
) -> BucketAccessControlInsertCall<'a, C> {
self._request = new_value;
self
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketAccessControlInsertCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketAccessControlInsertCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketAccessControlInsertCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketAccessControlInsertCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketAccessControlInsertCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketAccessControlInsertCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketAccessControlInsertCall<'a, C> {
self._scopes.clear();
self
}
}
/// Retrieves ACL entries on the specified bucket.
///
/// A builder for the *list* method supported by a *bucketAccessControl* resource.
/// It is not used directly, but through a [`BucketAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.bucket_access_controls().list("bucket")
/// .user_project("dolore")
/// .doit().await;
/// # }
/// ```
pub struct BucketAccessControlListCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketAccessControlListCall<'a, C> {}
impl<'a, C> BucketAccessControlListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, BucketAccessControls)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.bucketAccessControls.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "bucket", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/acl";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketAccessControlListCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketAccessControlListCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketAccessControlListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketAccessControlListCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketAccessControlListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketAccessControlListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketAccessControlListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Patches an ACL entry on the specified bucket.
///
/// A builder for the *patch* method supported by a *bucketAccessControl* resource.
/// It is not used directly, but through a [`BucketAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::BucketAccessControl;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = BucketAccessControl::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.bucket_access_controls().patch(req, "bucket", "entity")
/// .user_project("amet.")
/// .doit().await;
/// # }
/// ```
pub struct BucketAccessControlPatchCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: BucketAccessControl,
_bucket: String,
_entity: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketAccessControlPatchCall<'a, C> {}
impl<'a, C> BucketAccessControlPatchCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, BucketAccessControl)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.bucketAccessControls.patch",
http_method: hyper::Method::PATCH,
});
for &field in ["alt", "bucket", "entity", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("entity", self._entity);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/acl/{entity}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{entity}", "entity")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["entity", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PATCH)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: BucketAccessControl,
) -> BucketAccessControlPatchCall<'a, C> {
self._request = new_value;
self
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketAccessControlPatchCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
///
/// Sets the *entity* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn entity(mut self, new_value: &str) -> BucketAccessControlPatchCall<'a, C> {
self._entity = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketAccessControlPatchCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketAccessControlPatchCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketAccessControlPatchCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketAccessControlPatchCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketAccessControlPatchCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketAccessControlPatchCall<'a, C> {
self._scopes.clear();
self
}
}
/// Updates an ACL entry on the specified bucket.
///
/// A builder for the *update* method supported by a *bucketAccessControl* resource.
/// It is not used directly, but through a [`BucketAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::BucketAccessControl;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = BucketAccessControl::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.bucket_access_controls().update(req, "bucket", "entity")
/// .user_project("dolor")
/// .doit().await;
/// # }
/// ```
pub struct BucketAccessControlUpdateCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: BucketAccessControl,
_bucket: String,
_entity: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketAccessControlUpdateCall<'a, C> {}
impl<'a, C> BucketAccessControlUpdateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, BucketAccessControl)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.bucketAccessControls.update",
http_method: hyper::Method::PUT,
});
for &field in ["alt", "bucket", "entity", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("entity", self._entity);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/acl/{entity}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{entity}", "entity")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["entity", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PUT)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: BucketAccessControl,
) -> BucketAccessControlUpdateCall<'a, C> {
self._request = new_value;
self
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketAccessControlUpdateCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
///
/// Sets the *entity* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn entity(mut self, new_value: &str) -> BucketAccessControlUpdateCall<'a, C> {
self._entity = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketAccessControlUpdateCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketAccessControlUpdateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketAccessControlUpdateCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketAccessControlUpdateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketAccessControlUpdateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketAccessControlUpdateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Deletes an empty bucket. Deletions are permanent unless soft delete is enabled on the bucket.
///
/// A builder for the *delete* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().delete("bucket")
/// .user_project("et")
/// .if_metageneration_not_match(-95)
/// .if_metageneration_match(-15)
/// .doit().await;
/// # }
/// ```
pub struct BucketDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_user_project: Option<String>,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketDeleteCall<'a, C> {}
impl<'a, C> BucketDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<common::Response> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.delete",
http_method: hyper::Method::DELETE,
});
for &field in [
"bucket",
"userProject",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
params.extend(self._additional_params.iter());
let mut url = self.hub._base_url.clone() + "b/{bucket}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = common::Response::from_parts(parts, body);
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketDeleteCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketDeleteCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If set, only deletes the bucket if its metageneration does not match this value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> BucketDeleteCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// If set, only deletes the bucket if its metageneration matches this value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> BucketDeleteCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> BucketDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketDeleteCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Returns metadata for the specified bucket.
///
/// A builder for the *get* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().get("bucket")
/// .user_project("duo")
/// .soft_deleted(false)
/// .projection("vero")
/// .if_metageneration_not_match(-88)
/// .if_metageneration_match(-65)
/// .generation(-76)
/// .doit().await;
/// # }
/// ```
pub struct BucketGetCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_user_project: Option<String>,
_soft_deleted: Option<bool>,
_projection: Option<String>,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_generation: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketGetCall<'a, C> {}
impl<'a, C> BucketGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Bucket)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.get",
http_method: hyper::Method::GET,
});
for &field in [
"alt",
"bucket",
"userProject",
"softDeleted",
"projection",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
"generation",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(9 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._soft_deleted.as_ref() {
params.push("softDeleted", value.to_string());
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
if let Some(value) = self._generation.as_ref() {
params.push("generation", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketGetCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketGetCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If true, return the soft-deleted version of this bucket. The default is false. For more information, see [Soft Delete](https://cloud.google.com/storage/docs/soft-delete).
///
/// Sets the *soft deleted* query property to the given value.
pub fn soft_deleted(mut self, new_value: bool) -> BucketGetCall<'a, C> {
self._soft_deleted = Some(new_value);
self
}
/// Set of properties to return. Defaults to noAcl.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> BucketGetCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> BucketGetCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> BucketGetCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// If present, specifies the generation of the bucket. This is required if softDeleted is true.
///
/// Sets the *generation* query property to the given value.
pub fn generation(mut self, new_value: i64) -> BucketGetCall<'a, C> {
self._generation = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> BucketGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketGetCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Returns an IAM policy for the specified bucket.
///
/// A builder for the *getIamPolicy* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().get_iam_policy("bucket")
/// .user_project("Lorem")
/// .options_requested_policy_version(-29)
/// .doit().await;
/// # }
/// ```
pub struct BucketGetIamPolicyCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_user_project: Option<String>,
_options_requested_policy_version: Option<i32>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketGetIamPolicyCall<'a, C> {}
impl<'a, C> BucketGetIamPolicyCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Policy)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.getIamPolicy",
http_method: hyper::Method::GET,
});
for &field in [
"alt",
"bucket",
"userProject",
"optionsRequestedPolicyVersion",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._options_requested_policy_version.as_ref() {
params.push("optionsRequestedPolicyVersion", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/iam";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketGetIamPolicyCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketGetIamPolicyCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The IAM policy format version to be returned. If the optionsRequestedPolicyVersion is for an older version that doesn't support part of the requested IAM policy, the request fails.
///
/// Sets the *options requested policy version* query property to the given value.
pub fn options_requested_policy_version(
mut self,
new_value: i32,
) -> BucketGetIamPolicyCall<'a, C> {
self._options_requested_policy_version = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketGetIamPolicyCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketGetIamPolicyCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketGetIamPolicyCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketGetIamPolicyCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketGetIamPolicyCall<'a, C> {
self._scopes.clear();
self
}
}
/// Returns the storage layout configuration for the specified bucket. Note that this operation requires storage.objects.list permission.
///
/// A builder for the *getStorageLayout* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().get_storage_layout("bucket")
/// .prefix("ipsum")
/// .doit().await;
/// # }
/// ```
pub struct BucketGetStorageLayoutCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_prefix: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketGetStorageLayoutCall<'a, C> {}
impl<'a, C> BucketGetStorageLayoutCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, BucketStorageLayout)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.getStorageLayout",
http_method: hyper::Method::GET,
});
for &field in ["alt", "bucket", "prefix"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._prefix.as_ref() {
params.push("prefix", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/storageLayout";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketGetStorageLayoutCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// An optional prefix used for permission check. It is useful when the caller only has storage.objects.list permission under a specific prefix.
///
/// Sets the *prefix* query property to the given value.
pub fn prefix(mut self, new_value: &str) -> BucketGetStorageLayoutCall<'a, C> {
self._prefix = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketGetStorageLayoutCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketGetStorageLayoutCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketGetStorageLayoutCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketGetStorageLayoutCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketGetStorageLayoutCall<'a, C> {
self._scopes.clear();
self
}
}
/// Creates a new bucket.
///
/// A builder for the *insert* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Bucket;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Bucket::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().insert(req, "project")
/// .user_project("takimata")
/// .projection("consetetur")
/// .predefined_default_object_acl("voluptua.")
/// .predefined_acl("et")
/// .enable_object_retention(false)
/// .doit().await;
/// # }
/// ```
pub struct BucketInsertCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Bucket,
_project: String,
_user_project: Option<String>,
_projection: Option<String>,
_predefined_default_object_acl: Option<String>,
_predefined_acl: Option<String>,
_enable_object_retention: Option<bool>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketInsertCall<'a, C> {}
impl<'a, C> BucketInsertCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Bucket)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.insert",
http_method: hyper::Method::POST,
});
for &field in [
"alt",
"project",
"userProject",
"projection",
"predefinedDefaultObjectAcl",
"predefinedAcl",
"enableObjectRetention",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(9 + self._additional_params.len());
params.push("project", self._project);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._predefined_default_object_acl.as_ref() {
params.push("predefinedDefaultObjectAcl", value);
}
if let Some(value) = self._predefined_acl.as_ref() {
params.push("predefinedAcl", value);
}
if let Some(value) = self._enable_object_retention.as_ref() {
params.push("enableObjectRetention", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Bucket) -> BucketInsertCall<'a, C> {
self._request = new_value;
self
}
/// A valid API project identifier.
///
/// Sets the *project* query property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> BucketInsertCall<'a, C> {
self._project = new_value.to_string();
self
}
/// The project to be billed for this request.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketInsertCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// Set of properties to return. Defaults to noAcl, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to full.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> BucketInsertCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// Apply a predefined set of default object access controls to this bucket.
///
/// Sets the *predefined default object acl* query property to the given value.
pub fn predefined_default_object_acl(mut self, new_value: &str) -> BucketInsertCall<'a, C> {
self._predefined_default_object_acl = Some(new_value.to_string());
self
}
/// Apply a predefined set of access controls to this bucket.
///
/// Sets the *predefined acl* query property to the given value.
pub fn predefined_acl(mut self, new_value: &str) -> BucketInsertCall<'a, C> {
self._predefined_acl = Some(new_value.to_string());
self
}
/// When set to true, object retention is enabled for this bucket.
///
/// Sets the *enable object retention* query property to the given value.
pub fn enable_object_retention(mut self, new_value: bool) -> BucketInsertCall<'a, C> {
self._enable_object_retention = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> BucketInsertCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketInsertCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketInsertCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketInsertCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketInsertCall<'a, C> {
self._scopes.clear();
self
}
}
/// Retrieves a list of buckets for a given project.
///
/// A builder for the *list* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().list("project")
/// .user_project("sed")
/// .soft_deleted(true)
/// .return_partial_success(false)
/// .projection("accusam")
/// .prefix("voluptua.")
/// .page_token("dolore")
/// .max_results(67)
/// .doit().await;
/// # }
/// ```
pub struct BucketListCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_project: String,
_user_project: Option<String>,
_soft_deleted: Option<bool>,
_return_partial_success: Option<bool>,
_projection: Option<String>,
_prefix: Option<String>,
_page_token: Option<String>,
_max_results: Option<u32>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketListCall<'a, C> {}
impl<'a, C> BucketListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Buckets)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.list",
http_method: hyper::Method::GET,
});
for &field in [
"alt",
"project",
"userProject",
"softDeleted",
"returnPartialSuccess",
"projection",
"prefix",
"pageToken",
"maxResults",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(10 + self._additional_params.len());
params.push("project", self._project);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._soft_deleted.as_ref() {
params.push("softDeleted", value.to_string());
}
if let Some(value) = self._return_partial_success.as_ref() {
params.push("returnPartialSuccess", value.to_string());
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._prefix.as_ref() {
params.push("prefix", value);
}
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._max_results.as_ref() {
params.push("maxResults", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// A valid API project identifier.
///
/// Sets the *project* query property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> BucketListCall<'a, C> {
self._project = new_value.to_string();
self
}
/// The project to be billed for this request.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketListCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If true, only soft-deleted bucket versions will be returned. The default is false. For more information, see [Soft Delete](https://cloud.google.com/storage/docs/soft-delete).
///
/// Sets the *soft deleted* query property to the given value.
pub fn soft_deleted(mut self, new_value: bool) -> BucketListCall<'a, C> {
self._soft_deleted = Some(new_value);
self
}
/// If true, return a list of bucket resource names for buckets that are in unreachable locations.
///
/// Sets the *return partial success* query property to the given value.
pub fn return_partial_success(mut self, new_value: bool) -> BucketListCall<'a, C> {
self._return_partial_success = Some(new_value);
self
}
/// Set of properties to return. Defaults to noAcl.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> BucketListCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// Filter results to buckets whose names begin with this prefix.
///
/// Sets the *prefix* query property to the given value.
pub fn prefix(mut self, new_value: &str) -> BucketListCall<'a, C> {
self._prefix = Some(new_value.to_string());
self
}
/// A previously-returned page token representing part of the larger set of results to view.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> BucketListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Maximum number of buckets to return in a single response. The service will use this parameter or 1,000 items, whichever is smaller.
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: u32) -> BucketListCall<'a, C> {
self._max_results = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> BucketListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketListCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Locks retention policy on a bucket.
///
/// A builder for the *lockRetentionPolicy* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().lock_retention_policy("bucket", -78)
/// .user_project("amet.")
/// .doit().await;
/// # }
/// ```
pub struct BucketLockRetentionPolicyCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_if_metageneration_match: i64,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketLockRetentionPolicyCall<'a, C> {}
impl<'a, C> BucketLockRetentionPolicyCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Bucket)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.lockRetentionPolicy",
http_method: hyper::Method::POST,
});
for &field in ["alt", "bucket", "ifMetagenerationMatch", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push(
"ifMetagenerationMatch",
self._if_metageneration_match.to_string(),
);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/lockRetentionPolicy";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketLockRetentionPolicyCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Makes the operation conditional on whether bucket's current metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn if_metageneration_match(
mut self,
new_value: i64,
) -> BucketLockRetentionPolicyCall<'a, C> {
self._if_metageneration_match = new_value;
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketLockRetentionPolicyCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketLockRetentionPolicyCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketLockRetentionPolicyCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketLockRetentionPolicyCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketLockRetentionPolicyCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketLockRetentionPolicyCall<'a, C> {
self._scopes.clear();
self
}
}
/// Patches a bucket. Changes to the bucket will be readable immediately after writing, but configuration changes may take time to propagate.
///
/// A builder for the *patch* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Bucket;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Bucket::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().patch(req, "bucket")
/// .user_project("sadipscing")
/// .projection("Lorem")
/// .predefined_default_object_acl("invidunt")
/// .predefined_acl("no")
/// .if_metageneration_not_match(-7)
/// .if_metageneration_match(-27)
/// .doit().await;
/// # }
/// ```
pub struct BucketPatchCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Bucket,
_bucket: String,
_user_project: Option<String>,
_projection: Option<String>,
_predefined_default_object_acl: Option<String>,
_predefined_acl: Option<String>,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketPatchCall<'a, C> {}
impl<'a, C> BucketPatchCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Bucket)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.patch",
http_method: hyper::Method::PATCH,
});
for &field in [
"alt",
"bucket",
"userProject",
"projection",
"predefinedDefaultObjectAcl",
"predefinedAcl",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(10 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._predefined_default_object_acl.as_ref() {
params.push("predefinedDefaultObjectAcl", value);
}
if let Some(value) = self._predefined_acl.as_ref() {
params.push("predefinedAcl", value);
}
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PATCH)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Bucket) -> BucketPatchCall<'a, C> {
self._request = new_value;
self
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketPatchCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketPatchCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// Set of properties to return. Defaults to full.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> BucketPatchCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// Apply a predefined set of default object access controls to this bucket.
///
/// Sets the *predefined default object acl* query property to the given value.
pub fn predefined_default_object_acl(mut self, new_value: &str) -> BucketPatchCall<'a, C> {
self._predefined_default_object_acl = Some(new_value.to_string());
self
}
/// Apply a predefined set of access controls to this bucket.
///
/// Sets the *predefined acl* query property to the given value.
pub fn predefined_acl(mut self, new_value: &str) -> BucketPatchCall<'a, C> {
self._predefined_acl = Some(new_value.to_string());
self
}
/// Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> BucketPatchCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> BucketPatchCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> BucketPatchCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketPatchCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketPatchCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketPatchCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketPatchCall<'a, C> {
self._scopes.clear();
self
}
}
/// Initiates a long-running Relocate Bucket operation on the specified bucket.
///
/// A builder for the *relocate* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::RelocateBucketRequest;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = RelocateBucketRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().relocate(req, "bucket")
/// .doit().await;
/// # }
/// ```
pub struct BucketRelocateCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: RelocateBucketRequest,
_bucket: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketRelocateCall<'a, C> {}
impl<'a, C> BucketRelocateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, GoogleLongrunningOperation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.relocate",
http_method: hyper::Method::POST,
});
for &field in ["alt", "bucket"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/relocate";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: RelocateBucketRequest) -> BucketRelocateCall<'a, C> {
self._request = new_value;
self
}
/// Name of the bucket to be moved.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketRelocateCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketRelocateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketRelocateCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketRelocateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketRelocateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketRelocateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Restores a soft-deleted bucket.
///
/// A builder for the *restore* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().restore("bucket", -35)
/// .user_project("tempor")
/// .projection("aliquyam")
/// .doit().await;
/// # }
/// ```
pub struct BucketRestoreCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_generation: i64,
_user_project: Option<String>,
_projection: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketRestoreCall<'a, C> {}
impl<'a, C> BucketRestoreCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Bucket)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.restore",
http_method: hyper::Method::POST,
});
for &field in ["alt", "bucket", "generation", "userProject", "projection"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("generation", self._generation.to_string());
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/restore";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketRestoreCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Generation of a bucket.
///
/// Sets the *generation* query property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn generation(mut self, new_value: i64) -> BucketRestoreCall<'a, C> {
self._generation = new_value;
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketRestoreCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// Set of properties to return. Defaults to full.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> BucketRestoreCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> BucketRestoreCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketRestoreCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketRestoreCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketRestoreCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketRestoreCall<'a, C> {
self._scopes.clear();
self
}
}
/// Updates an IAM policy for the specified bucket.
///
/// A builder for the *setIamPolicy* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Policy;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Policy::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().set_iam_policy(req, "bucket")
/// .user_project("et")
/// .doit().await;
/// # }
/// ```
pub struct BucketSetIamPolicyCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Policy,
_bucket: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketSetIamPolicyCall<'a, C> {}
impl<'a, C> BucketSetIamPolicyCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Policy)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.setIamPolicy",
http_method: hyper::Method::PUT,
});
for &field in ["alt", "bucket", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/iam";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PUT)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Policy) -> BucketSetIamPolicyCall<'a, C> {
self._request = new_value;
self
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketSetIamPolicyCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketSetIamPolicyCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketSetIamPolicyCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketSetIamPolicyCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketSetIamPolicyCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketSetIamPolicyCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketSetIamPolicyCall<'a, C> {
self._scopes.clear();
self
}
}
/// Tests a set of permissions on the given bucket to see which, if any, are held by the caller.
///
/// A builder for the *testIamPermissions* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().test_iam_permissions("bucket", &vec!["Lorem".into()])
/// .user_project("est")
/// .doit().await;
/// # }
/// ```
pub struct BucketTestIamPermissionCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_permissions: Vec<String>,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketTestIamPermissionCall<'a, C> {}
impl<'a, C> BucketTestIamPermissionCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, TestIamPermissionsResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.testIamPermissions",
http_method: hyper::Method::GET,
});
for &field in ["alt", "bucket", "permissions", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
if !self._permissions.is_empty() {
for f in self._permissions.iter() {
params.push("permissions", f);
}
}
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/iam/testPermissions";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketTestIamPermissionCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Permissions to test.
///
/// Append the given value to the *permissions* query property.
/// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn add_permissions(mut self, new_value: &str) -> BucketTestIamPermissionCall<'a, C> {
self._permissions.push(new_value.to_string());
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketTestIamPermissionCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketTestIamPermissionCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketTestIamPermissionCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketTestIamPermissionCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketTestIamPermissionCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketTestIamPermissionCall<'a, C> {
self._scopes.clear();
self
}
}
/// Updates a bucket. Changes to the bucket will be readable immediately after writing, but configuration changes may take time to propagate.
///
/// A builder for the *update* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Bucket;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Bucket::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().update(req, "bucket")
/// .user_project("diam")
/// .projection("dolores")
/// .predefined_default_object_acl("dolores")
/// .predefined_acl("et")
/// .if_metageneration_not_match(-93)
/// .if_metageneration_match(-11)
/// .doit().await;
/// # }
/// ```
pub struct BucketUpdateCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Bucket,
_bucket: String,
_user_project: Option<String>,
_projection: Option<String>,
_predefined_default_object_acl: Option<String>,
_predefined_acl: Option<String>,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketUpdateCall<'a, C> {}
impl<'a, C> BucketUpdateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Bucket)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.update",
http_method: hyper::Method::PUT,
});
for &field in [
"alt",
"bucket",
"userProject",
"projection",
"predefinedDefaultObjectAcl",
"predefinedAcl",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(10 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._predefined_default_object_acl.as_ref() {
params.push("predefinedDefaultObjectAcl", value);
}
if let Some(value) = self._predefined_acl.as_ref() {
params.push("predefinedAcl", value);
}
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PUT)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Bucket) -> BucketUpdateCall<'a, C> {
self._request = new_value;
self
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketUpdateCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> BucketUpdateCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// Set of properties to return. Defaults to full.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> BucketUpdateCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// Apply a predefined set of default object access controls to this bucket.
///
/// Sets the *predefined default object acl* query property to the given value.
pub fn predefined_default_object_acl(mut self, new_value: &str) -> BucketUpdateCall<'a, C> {
self._predefined_default_object_acl = Some(new_value.to_string());
self
}
/// Apply a predefined set of access controls to this bucket.
///
/// Sets the *predefined acl* query property to the given value.
pub fn predefined_acl(mut self, new_value: &str) -> BucketUpdateCall<'a, C> {
self._predefined_acl = Some(new_value.to_string());
self
}
/// Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> BucketUpdateCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> BucketUpdateCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> BucketUpdateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketUpdateCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketUpdateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketUpdateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketUpdateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Starts asynchronous advancement of the relocate bucket operation in the case of required write downtime, to allow it to lock the bucket at the source location, and proceed with the bucket location swap. The server makes a best effort to advance the relocate bucket operation, but success is not guaranteed.
///
/// A builder for the *operations.advanceRelocateBucket* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::AdvanceRelocateBucketOperationRequest;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = AdvanceRelocateBucketOperationRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().operations_advance_relocate_bucket(req, "bucket", "operationId")
/// .doit().await;
/// # }
/// ```
pub struct BucketOperationAdvanceRelocateBucketCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: AdvanceRelocateBucketOperationRequest,
_bucket: String,
_operation_id: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketOperationAdvanceRelocateBucketCall<'a, C> {}
impl<'a, C> BucketOperationAdvanceRelocateBucketCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<common::Response> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.operations.advanceRelocateBucket",
http_method: hyper::Method::POST,
});
for &field in ["bucket", "operationId"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("operationId", self._operation_id);
params.extend(self._additional_params.iter());
let mut url = self.hub._base_url.clone()
+ "b/{bucket}/operations/{operationId}/advanceRelocateBucket";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in
[("{bucket}", "bucket"), ("{operationId}", "operationId")].iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["operationId", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = common::Response::from_parts(parts, body);
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: AdvanceRelocateBucketOperationRequest,
) -> BucketOperationAdvanceRelocateBucketCall<'a, C> {
self._request = new_value;
self
}
/// Name of the bucket to advance the relocate for.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketOperationAdvanceRelocateBucketCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// ID of the operation resource.
///
/// Sets the *operation id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn operation_id(
mut self,
new_value: &str,
) -> BucketOperationAdvanceRelocateBucketCall<'a, C> {
self._operation_id = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketOperationAdvanceRelocateBucketCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketOperationAdvanceRelocateBucketCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketOperationAdvanceRelocateBucketCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketOperationAdvanceRelocateBucketCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketOperationAdvanceRelocateBucketCall<'a, C> {
self._scopes.clear();
self
}
}
/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed.
///
/// A builder for the *operations.cancel* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().operations_cancel("bucket", "operationId")
/// .doit().await;
/// # }
/// ```
pub struct BucketOperationCancelCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_operation_id: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketOperationCancelCall<'a, C> {}
impl<'a, C> BucketOperationCancelCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<common::Response> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.operations.cancel",
http_method: hyper::Method::POST,
});
for &field in ["bucket", "operationId"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("operationId", self._operation_id);
params.extend(self._additional_params.iter());
let mut url = self.hub._base_url.clone() + "b/{bucket}/operations/{operationId}/cancel";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in
[("{bucket}", "bucket"), ("{operationId}", "operationId")].iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["operationId", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = common::Response::from_parts(parts, body);
dlg.finished(true);
return Ok(response);
}
}
}
}
/// The parent bucket of the operation resource.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketOperationCancelCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The ID of the operation resource.
///
/// Sets the *operation id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn operation_id(mut self, new_value: &str) -> BucketOperationCancelCall<'a, C> {
self._operation_id = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketOperationCancelCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketOperationCancelCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketOperationCancelCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketOperationCancelCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketOperationCancelCall<'a, C> {
self._scopes.clear();
self
}
}
/// Gets the latest state of a long-running operation.
///
/// A builder for the *operations.get* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().operations_get("bucket", "operationId")
/// .doit().await;
/// # }
/// ```
pub struct BucketOperationGetCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_operation_id: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketOperationGetCall<'a, C> {}
impl<'a, C> BucketOperationGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, GoogleLongrunningOperation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.operations.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "bucket", "operationId"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("operationId", self._operation_id);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/operations/{operationId}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in
[("{bucket}", "bucket"), ("{operationId}", "operationId")].iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["operationId", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// The parent bucket of the operation resource.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketOperationGetCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The ID of the operation resource.
///
/// Sets the *operation id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn operation_id(mut self, new_value: &str) -> BucketOperationGetCall<'a, C> {
self._operation_id = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketOperationGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketOperationGetCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketOperationGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketOperationGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketOperationGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Lists operations that match the specified filter in the request.
///
/// A builder for the *operations.list* method supported by a *bucket* resource.
/// It is not used directly, but through a [`BucketMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.buckets().operations_list("bucket")
/// .page_token("aliquyam")
/// .page_size(-69)
/// .filter("sadipscing")
/// .doit().await;
/// # }
/// ```
pub struct BucketOperationListCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_filter: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for BucketOperationListCall<'a, C> {}
impl<'a, C> BucketOperationListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(
mut self,
) -> common::Result<(common::Response, GoogleLongrunningListOperationsResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.buckets.operations.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "bucket", "pageToken", "pageSize", "filter"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
if let Some(value) = self._filter.as_ref() {
params.push("filter", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/operations";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket in which to look for operations.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> BucketOperationListCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// A previously-returned page token representing part of the larger set of results to view.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> BucketOperationListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Maximum number of items to return in a single page of responses. Fewer total results may be returned than requested. The service uses this parameter or 100 items, whichever is smaller.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> BucketOperationListCall<'a, C> {
self._page_size = Some(new_value);
self
}
/// A filter to narrow down results to a preferred subset. The filtering language is documented in more detail in [AIP-160](https://google.aip.dev/160).
///
/// Sets the *filter* query property to the given value.
pub fn filter(mut self, new_value: &str) -> BucketOperationListCall<'a, C> {
self._filter = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> BucketOperationListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> BucketOperationListCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> BucketOperationListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> BucketOperationListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> BucketOperationListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Stop watching resources through this channel
///
/// A builder for the *stop* method supported by a *channel* resource.
/// It is not used directly, but through a [`ChannelMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Channel;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Channel::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.channels().stop(req)
/// .doit().await;
/// # }
/// ```
pub struct ChannelStopCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Channel,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ChannelStopCall<'a, C> {}
impl<'a, C> ChannelStopCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<common::Response> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.channels.stop",
http_method: hyper::Method::POST,
});
for &field in [].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(2 + self._additional_params.len());
params.extend(self._additional_params.iter());
let mut url = self.hub._base_url.clone() + "channels/stop";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = common::Response::from_parts(parts, body);
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Channel) -> ChannelStopCall<'a, C> {
self._request = new_value;
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ChannelStopCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ChannelStopCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ChannelStopCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ChannelStopCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ChannelStopCall<'a, C> {
self._scopes.clear();
self
}
}
/// Permanently deletes the default object ACL entry for the specified entity on the specified bucket.
///
/// A builder for the *delete* method supported by a *defaultObjectAccessControl* resource.
/// It is not used directly, but through a [`DefaultObjectAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.default_object_access_controls().delete("bucket", "entity")
/// .user_project("amet")
/// .doit().await;
/// # }
/// ```
pub struct DefaultObjectAccessControlDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_entity: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for DefaultObjectAccessControlDeleteCall<'a, C> {}
impl<'a, C> DefaultObjectAccessControlDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<common::Response> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.defaultObjectAccessControls.delete",
http_method: hyper::Method::DELETE,
});
for &field in ["bucket", "entity", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("entity", self._entity);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
let mut url = self.hub._base_url.clone() + "b/{bucket}/defaultObjectAcl/{entity}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{entity}", "entity")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["entity", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = common::Response::from_parts(parts, body);
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> DefaultObjectAccessControlDeleteCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
///
/// Sets the *entity* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn entity(mut self, new_value: &str) -> DefaultObjectAccessControlDeleteCall<'a, C> {
self._entity = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> DefaultObjectAccessControlDeleteCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> DefaultObjectAccessControlDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> DefaultObjectAccessControlDeleteCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> DefaultObjectAccessControlDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> DefaultObjectAccessControlDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> DefaultObjectAccessControlDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Returns the default object ACL entry for the specified entity on the specified bucket.
///
/// A builder for the *get* method supported by a *defaultObjectAccessControl* resource.
/// It is not used directly, but through a [`DefaultObjectAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.default_object_access_controls().get("bucket", "entity")
/// .user_project("sea")
/// .doit().await;
/// # }
/// ```
pub struct DefaultObjectAccessControlGetCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_entity: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for DefaultObjectAccessControlGetCall<'a, C> {}
impl<'a, C> DefaultObjectAccessControlGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ObjectAccessControl)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.defaultObjectAccessControls.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "bucket", "entity", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("entity", self._entity);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/defaultObjectAcl/{entity}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{entity}", "entity")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["entity", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> DefaultObjectAccessControlGetCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
///
/// Sets the *entity* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn entity(mut self, new_value: &str) -> DefaultObjectAccessControlGetCall<'a, C> {
self._entity = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> DefaultObjectAccessControlGetCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> DefaultObjectAccessControlGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> DefaultObjectAccessControlGetCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> DefaultObjectAccessControlGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> DefaultObjectAccessControlGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> DefaultObjectAccessControlGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Creates a new default object ACL entry on the specified bucket.
///
/// A builder for the *insert* method supported by a *defaultObjectAccessControl* resource.
/// It is not used directly, but through a [`DefaultObjectAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::ObjectAccessControl;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = ObjectAccessControl::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.default_object_access_controls().insert(req, "bucket")
/// .user_project("consetetur")
/// .doit().await;
/// # }
/// ```
pub struct DefaultObjectAccessControlInsertCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: ObjectAccessControl,
_bucket: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for DefaultObjectAccessControlInsertCall<'a, C> {}
impl<'a, C> DefaultObjectAccessControlInsertCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ObjectAccessControl)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.defaultObjectAccessControls.insert",
http_method: hyper::Method::POST,
});
for &field in ["alt", "bucket", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/defaultObjectAcl";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: ObjectAccessControl,
) -> DefaultObjectAccessControlInsertCall<'a, C> {
self._request = new_value;
self
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> DefaultObjectAccessControlInsertCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> DefaultObjectAccessControlInsertCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> DefaultObjectAccessControlInsertCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> DefaultObjectAccessControlInsertCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> DefaultObjectAccessControlInsertCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> DefaultObjectAccessControlInsertCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> DefaultObjectAccessControlInsertCall<'a, C> {
self._scopes.clear();
self
}
}
/// Retrieves default object ACL entries on the specified bucket.
///
/// A builder for the *list* method supported by a *defaultObjectAccessControl* resource.
/// It is not used directly, but through a [`DefaultObjectAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.default_object_access_controls().list("bucket")
/// .user_project("est")
/// .if_metageneration_not_match(-82)
/// .if_metageneration_match(-94)
/// .doit().await;
/// # }
/// ```
pub struct DefaultObjectAccessControlListCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_user_project: Option<String>,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for DefaultObjectAccessControlListCall<'a, C> {}
impl<'a, C> DefaultObjectAccessControlListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ObjectAccessControls)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.defaultObjectAccessControls.list",
http_method: hyper::Method::GET,
});
for &field in [
"alt",
"bucket",
"userProject",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/defaultObjectAcl";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> DefaultObjectAccessControlListCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> DefaultObjectAccessControlListCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If present, only return default ACL listing if the bucket's current metageneration does not match the given value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(
mut self,
new_value: i64,
) -> DefaultObjectAccessControlListCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// If present, only return default ACL listing if the bucket's current metageneration matches this value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(
mut self,
new_value: i64,
) -> DefaultObjectAccessControlListCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> DefaultObjectAccessControlListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> DefaultObjectAccessControlListCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> DefaultObjectAccessControlListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> DefaultObjectAccessControlListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> DefaultObjectAccessControlListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Patches a default object ACL entry on the specified bucket.
///
/// A builder for the *patch* method supported by a *defaultObjectAccessControl* resource.
/// It is not used directly, but through a [`DefaultObjectAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::ObjectAccessControl;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = ObjectAccessControl::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.default_object_access_controls().patch(req, "bucket", "entity")
/// .user_project("est")
/// .doit().await;
/// # }
/// ```
pub struct DefaultObjectAccessControlPatchCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: ObjectAccessControl,
_bucket: String,
_entity: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for DefaultObjectAccessControlPatchCall<'a, C> {}
impl<'a, C> DefaultObjectAccessControlPatchCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ObjectAccessControl)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.defaultObjectAccessControls.patch",
http_method: hyper::Method::PATCH,
});
for &field in ["alt", "bucket", "entity", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("entity", self._entity);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/defaultObjectAcl/{entity}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{entity}", "entity")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["entity", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PATCH)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: ObjectAccessControl,
) -> DefaultObjectAccessControlPatchCall<'a, C> {
self._request = new_value;
self
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> DefaultObjectAccessControlPatchCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
///
/// Sets the *entity* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn entity(mut self, new_value: &str) -> DefaultObjectAccessControlPatchCall<'a, C> {
self._entity = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> DefaultObjectAccessControlPatchCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> DefaultObjectAccessControlPatchCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> DefaultObjectAccessControlPatchCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> DefaultObjectAccessControlPatchCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> DefaultObjectAccessControlPatchCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> DefaultObjectAccessControlPatchCall<'a, C> {
self._scopes.clear();
self
}
}
/// Updates a default object ACL entry on the specified bucket.
///
/// A builder for the *update* method supported by a *defaultObjectAccessControl* resource.
/// It is not used directly, but through a [`DefaultObjectAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::ObjectAccessControl;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = ObjectAccessControl::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.default_object_access_controls().update(req, "bucket", "entity")
/// .user_project("eos")
/// .doit().await;
/// # }
/// ```
pub struct DefaultObjectAccessControlUpdateCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: ObjectAccessControl,
_bucket: String,
_entity: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for DefaultObjectAccessControlUpdateCall<'a, C> {}
impl<'a, C> DefaultObjectAccessControlUpdateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ObjectAccessControl)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.defaultObjectAccessControls.update",
http_method: hyper::Method::PUT,
});
for &field in ["alt", "bucket", "entity", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("entity", self._entity);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/defaultObjectAcl/{entity}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{entity}", "entity")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["entity", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PUT)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: ObjectAccessControl,
) -> DefaultObjectAccessControlUpdateCall<'a, C> {
self._request = new_value;
self
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> DefaultObjectAccessControlUpdateCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
///
/// Sets the *entity* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn entity(mut self, new_value: &str) -> DefaultObjectAccessControlUpdateCall<'a, C> {
self._entity = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> DefaultObjectAccessControlUpdateCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> DefaultObjectAccessControlUpdateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> DefaultObjectAccessControlUpdateCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> DefaultObjectAccessControlUpdateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> DefaultObjectAccessControlUpdateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> DefaultObjectAccessControlUpdateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Permanently deletes a folder. Only applicable to buckets with hierarchical namespace enabled.
///
/// A builder for the *delete* method supported by a *folder* resource.
/// It is not used directly, but through a [`FolderMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.folders().delete("bucket", "folder")
/// .if_metageneration_not_match(-15)
/// .if_metageneration_match(-19)
/// .doit().await;
/// # }
/// ```
pub struct FolderDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_folder: String,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for FolderDeleteCall<'a, C> {}
impl<'a, C> FolderDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<common::Response> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.folders.delete",
http_method: hyper::Method::DELETE,
});
for &field in [
"bucket",
"folder",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("folder", self._folder);
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
params.extend(self._additional_params.iter());
let mut url = self.hub._base_url.clone() + "b/{bucket}/folders/{folder}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{folder}", "folder")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["folder", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = common::Response::from_parts(parts, body);
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket in which the folder resides.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> FolderDeleteCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of a folder.
///
/// Sets the *folder* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn folder(mut self, new_value: &str) -> FolderDeleteCall<'a, C> {
self._folder = new_value.to_string();
self
}
/// If set, only deletes the folder if its metageneration does not match this value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> FolderDeleteCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// If set, only deletes the folder if its metageneration matches this value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> FolderDeleteCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> FolderDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> FolderDeleteCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> FolderDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> FolderDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> FolderDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Returns metadata for the specified folder. Only applicable to buckets with hierarchical namespace enabled.
///
/// A builder for the *get* method supported by a *folder* resource.
/// It is not used directly, but through a [`FolderMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.folders().get("bucket", "folder")
/// .if_metageneration_not_match(-10)
/// .if_metageneration_match(-74)
/// .doit().await;
/// # }
/// ```
pub struct FolderGetCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_folder: String,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for FolderGetCall<'a, C> {}
impl<'a, C> FolderGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Folder)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.folders.get",
http_method: hyper::Method::GET,
});
for &field in [
"alt",
"bucket",
"folder",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("folder", self._folder);
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/folders/{folder}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{folder}", "folder")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["folder", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket in which the folder resides.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> FolderGetCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of a folder.
///
/// Sets the *folder* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn folder(mut self, new_value: &str) -> FolderGetCall<'a, C> {
self._folder = new_value.to_string();
self
}
/// Makes the return of the folder metadata conditional on whether the folder's current metageneration does not match the given value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> FolderGetCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// Makes the return of the folder metadata conditional on whether the folder's current metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> FolderGetCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> FolderGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> FolderGetCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> FolderGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> FolderGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> FolderGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Creates a new folder. Only applicable to buckets with hierarchical namespace enabled.
///
/// A builder for the *insert* method supported by a *folder* resource.
/// It is not used directly, but through a [`FolderMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Folder;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Folder::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.folders().insert(req, "bucket")
/// .recursive(false)
/// .doit().await;
/// # }
/// ```
pub struct FolderInsertCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Folder,
_bucket: String,
_recursive: Option<bool>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for FolderInsertCall<'a, C> {}
impl<'a, C> FolderInsertCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Folder)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.folders.insert",
http_method: hyper::Method::POST,
});
for &field in ["alt", "bucket", "recursive"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._recursive.as_ref() {
params.push("recursive", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/folders";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Folder) -> FolderInsertCall<'a, C> {
self._request = new_value;
self
}
/// Name of the bucket in which the folder resides.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> FolderInsertCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// If true, any parent folder which doesn't exist will be created automatically.
///
/// Sets the *recursive* query property to the given value.
pub fn recursive(mut self, new_value: bool) -> FolderInsertCall<'a, C> {
self._recursive = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> FolderInsertCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> FolderInsertCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> FolderInsertCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> FolderInsertCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> FolderInsertCall<'a, C> {
self._scopes.clear();
self
}
}
/// Retrieves a list of folders matching the criteria. Only applicable to buckets with hierarchical namespace enabled.
///
/// A builder for the *list* method supported by a *folder* resource.
/// It is not used directly, but through a [`FolderMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.folders().list("bucket")
/// .start_offset("Lorem")
/// .prefix("accusam")
/// .page_token("amet")
/// .page_size(-31)
/// .end_offset("dolores")
/// .delimiter("erat")
/// .doit().await;
/// # }
/// ```
pub struct FolderListCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_start_offset: Option<String>,
_prefix: Option<String>,
_page_token: Option<String>,
_page_size: Option<i32>,
_end_offset: Option<String>,
_delimiter: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for FolderListCall<'a, C> {}
impl<'a, C> FolderListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Folders)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.folders.list",
http_method: hyper::Method::GET,
});
for &field in [
"alt",
"bucket",
"startOffset",
"prefix",
"pageToken",
"pageSize",
"endOffset",
"delimiter",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(9 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._start_offset.as_ref() {
params.push("startOffset", value);
}
if let Some(value) = self._prefix.as_ref() {
params.push("prefix", value);
}
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
if let Some(value) = self._end_offset.as_ref() {
params.push("endOffset", value);
}
if let Some(value) = self._delimiter.as_ref() {
params.push("delimiter", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/folders";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket in which to look for folders.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> FolderListCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Filter results to folders whose names are lexicographically equal to or after startOffset. If endOffset is also set, the folders listed will have names between startOffset (inclusive) and endOffset (exclusive).
///
/// Sets the *start offset* query property to the given value.
pub fn start_offset(mut self, new_value: &str) -> FolderListCall<'a, C> {
self._start_offset = Some(new_value.to_string());
self
}
/// Filter results to folders whose paths begin with this prefix. If set, the value must either be an empty string or end with a '/'.
///
/// Sets the *prefix* query property to the given value.
pub fn prefix(mut self, new_value: &str) -> FolderListCall<'a, C> {
self._prefix = Some(new_value.to_string());
self
}
/// A previously-returned page token representing part of the larger set of results to view.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> FolderListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Maximum number of items to return in a single page of responses.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> FolderListCall<'a, C> {
self._page_size = Some(new_value);
self
}
/// Filter results to folders whose names are lexicographically before endOffset. If startOffset is also set, the folders listed will have names between startOffset (inclusive) and endOffset (exclusive).
///
/// Sets the *end offset* query property to the given value.
pub fn end_offset(mut self, new_value: &str) -> FolderListCall<'a, C> {
self._end_offset = Some(new_value.to_string());
self
}
/// Returns results in a directory-like mode. The only supported value is '/'. If set, items will only contain folders that either exactly match the prefix, or are one level below the prefix.
///
/// Sets the *delimiter* query property to the given value.
pub fn delimiter(mut self, new_value: &str) -> FolderListCall<'a, C> {
self._delimiter = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> FolderListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> FolderListCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> FolderListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> FolderListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> FolderListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Renames a source folder to a destination folder. Only applicable to buckets with hierarchical namespace enabled.
///
/// A builder for the *rename* method supported by a *folder* resource.
/// It is not used directly, but through a [`FolderMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.folders().rename("bucket", "sourceFolder", "destinationFolder")
/// .if_source_metageneration_not_match(-51)
/// .if_source_metageneration_match(-22)
/// .doit().await;
/// # }
/// ```
pub struct FolderRenameCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_source_folder: String,
_destination_folder: String,
_if_source_metageneration_not_match: Option<i64>,
_if_source_metageneration_match: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for FolderRenameCall<'a, C> {}
impl<'a, C> FolderRenameCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, GoogleLongrunningOperation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.folders.rename",
http_method: hyper::Method::POST,
});
for &field in [
"alt",
"bucket",
"sourceFolder",
"destinationFolder",
"ifSourceMetagenerationNotMatch",
"ifSourceMetagenerationMatch",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(7 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("sourceFolder", self._source_folder);
params.push("destinationFolder", self._destination_folder);
if let Some(value) = self._if_source_metageneration_not_match.as_ref() {
params.push("ifSourceMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_source_metageneration_match.as_ref() {
params.push("ifSourceMetagenerationMatch", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone()
+ "b/{bucket}/folders/{sourceFolder}/renameTo/folders/{destinationFolder}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [
("{bucket}", "bucket"),
("{sourceFolder}", "sourceFolder"),
("{destinationFolder}", "destinationFolder"),
]
.iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["destinationFolder", "sourceFolder", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket in which the folders are in.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> FolderRenameCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the source folder.
///
/// Sets the *source folder* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn source_folder(mut self, new_value: &str) -> FolderRenameCall<'a, C> {
self._source_folder = new_value.to_string();
self
}
/// Name of the destination folder.
///
/// Sets the *destination folder* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn destination_folder(mut self, new_value: &str) -> FolderRenameCall<'a, C> {
self._destination_folder = new_value.to_string();
self
}
/// Makes the operation conditional on whether the source object's current metageneration does not match the given value.
///
/// Sets the *if source metageneration not match* query property to the given value.
pub fn if_source_metageneration_not_match(mut self, new_value: i64) -> FolderRenameCall<'a, C> {
self._if_source_metageneration_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the source object's current metageneration matches the given value.
///
/// Sets the *if source metageneration match* query property to the given value.
pub fn if_source_metageneration_match(mut self, new_value: i64) -> FolderRenameCall<'a, C> {
self._if_source_metageneration_match = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> FolderRenameCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> FolderRenameCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> FolderRenameCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> FolderRenameCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> FolderRenameCall<'a, C> {
self._scopes.clear();
self
}
}
/// Permanently deletes a managed folder.
///
/// A builder for the *delete* method supported by a *managedFolder* resource.
/// It is not used directly, but through a [`ManagedFolderMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.managed_folders().delete("bucket", "managedFolder")
/// .if_metageneration_not_match(-22)
/// .if_metageneration_match(-48)
/// .allow_non_empty(false)
/// .doit().await;
/// # }
/// ```
pub struct ManagedFolderDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_managed_folder: String,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_allow_non_empty: Option<bool>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ManagedFolderDeleteCall<'a, C> {}
impl<'a, C> ManagedFolderDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<common::Response> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.managedFolders.delete",
http_method: hyper::Method::DELETE,
});
for &field in [
"bucket",
"managedFolder",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
"allowNonEmpty",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("managedFolder", self._managed_folder);
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
if let Some(value) = self._allow_non_empty.as_ref() {
params.push("allowNonEmpty", value.to_string());
}
params.extend(self._additional_params.iter());
let mut url = self.hub._base_url.clone() + "b/{bucket}/managedFolders/{managedFolder}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in
[("{bucket}", "bucket"), ("{managedFolder}", "managedFolder")].iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["managedFolder", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = common::Response::from_parts(parts, body);
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket containing the managed folder.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ManagedFolderDeleteCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The managed folder name/path.
///
/// Sets the *managed folder* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn managed_folder(mut self, new_value: &str) -> ManagedFolderDeleteCall<'a, C> {
self._managed_folder = new_value.to_string();
self
}
/// If set, only deletes the managed folder if its metageneration does not match this value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> ManagedFolderDeleteCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// If set, only deletes the managed folder if its metageneration matches this value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> ManagedFolderDeleteCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// Allows the deletion of a managed folder even if it is not empty. A managed folder is empty if there are no objects or managed folders that it applies to. Callers must have storage.managedFolders.setIamPolicy permission.
///
/// Sets the *allow non empty* query property to the given value.
pub fn allow_non_empty(mut self, new_value: bool) -> ManagedFolderDeleteCall<'a, C> {
self._allow_non_empty = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ManagedFolderDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ManagedFolderDeleteCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ManagedFolderDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ManagedFolderDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ManagedFolderDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Returns metadata of the specified managed folder.
///
/// A builder for the *get* method supported by a *managedFolder* resource.
/// It is not used directly, but through a [`ManagedFolderMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.managed_folders().get("bucket", "managedFolder")
/// .if_metageneration_not_match(-22)
/// .if_metageneration_match(-12)
/// .doit().await;
/// # }
/// ```
pub struct ManagedFolderGetCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_managed_folder: String,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ManagedFolderGetCall<'a, C> {}
impl<'a, C> ManagedFolderGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ManagedFolder)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.managedFolders.get",
http_method: hyper::Method::GET,
});
for &field in [
"alt",
"bucket",
"managedFolder",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("managedFolder", self._managed_folder);
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/managedFolders/{managedFolder}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in
[("{bucket}", "bucket"), ("{managedFolder}", "managedFolder")].iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["managedFolder", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket containing the managed folder.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ManagedFolderGetCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The managed folder name/path.
///
/// Sets the *managed folder* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn managed_folder(mut self, new_value: &str) -> ManagedFolderGetCall<'a, C> {
self._managed_folder = new_value.to_string();
self
}
/// Makes the return of the managed folder metadata conditional on whether the managed folder's current metageneration does not match the given value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> ManagedFolderGetCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// Makes the return of the managed folder metadata conditional on whether the managed folder's current metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> ManagedFolderGetCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ManagedFolderGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ManagedFolderGetCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ManagedFolderGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ManagedFolderGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ManagedFolderGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Returns an IAM policy for the specified managed folder.
///
/// A builder for the *getIamPolicy* method supported by a *managedFolder* resource.
/// It is not used directly, but through a [`ManagedFolderMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.managed_folders().get_iam_policy("bucket", "managedFolder")
/// .user_project("consetetur")
/// .options_requested_policy_version(-98)
/// .doit().await;
/// # }
/// ```
pub struct ManagedFolderGetIamPolicyCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_managed_folder: String,
_user_project: Option<String>,
_options_requested_policy_version: Option<i32>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ManagedFolderGetIamPolicyCall<'a, C> {}
impl<'a, C> ManagedFolderGetIamPolicyCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Policy)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.managedFolders.getIamPolicy",
http_method: hyper::Method::GET,
});
for &field in [
"alt",
"bucket",
"managedFolder",
"userProject",
"optionsRequestedPolicyVersion",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("managedFolder", self._managed_folder);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._options_requested_policy_version.as_ref() {
params.push("optionsRequestedPolicyVersion", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/managedFolders/{managedFolder}/iam";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in
[("{bucket}", "bucket"), ("{managedFolder}", "managedFolder")].iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["managedFolder", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket containing the managed folder.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ManagedFolderGetIamPolicyCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The managed folder name/path.
///
/// Sets the *managed folder* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn managed_folder(mut self, new_value: &str) -> ManagedFolderGetIamPolicyCall<'a, C> {
self._managed_folder = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ManagedFolderGetIamPolicyCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The IAM policy format version to be returned. If the optionsRequestedPolicyVersion is for an older version that doesn't support part of the requested IAM policy, the request fails.
///
/// Sets the *options requested policy version* query property to the given value.
pub fn options_requested_policy_version(
mut self,
new_value: i32,
) -> ManagedFolderGetIamPolicyCall<'a, C> {
self._options_requested_policy_version = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ManagedFolderGetIamPolicyCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ManagedFolderGetIamPolicyCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ManagedFolderGetIamPolicyCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ManagedFolderGetIamPolicyCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ManagedFolderGetIamPolicyCall<'a, C> {
self._scopes.clear();
self
}
}
/// Creates a new managed folder.
///
/// A builder for the *insert* method supported by a *managedFolder* resource.
/// It is not used directly, but through a [`ManagedFolderMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::ManagedFolder;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = ManagedFolder::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.managed_folders().insert(req, "bucket")
/// .doit().await;
/// # }
/// ```
pub struct ManagedFolderInsertCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: ManagedFolder,
_bucket: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ManagedFolderInsertCall<'a, C> {}
impl<'a, C> ManagedFolderInsertCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ManagedFolder)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.managedFolders.insert",
http_method: hyper::Method::POST,
});
for &field in ["alt", "bucket"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/managedFolders";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: ManagedFolder) -> ManagedFolderInsertCall<'a, C> {
self._request = new_value;
self
}
/// Name of the bucket containing the managed folder.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ManagedFolderInsertCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ManagedFolderInsertCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ManagedFolderInsertCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ManagedFolderInsertCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ManagedFolderInsertCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ManagedFolderInsertCall<'a, C> {
self._scopes.clear();
self
}
}
/// Lists managed folders in the given bucket.
///
/// A builder for the *list* method supported by a *managedFolder* resource.
/// It is not used directly, but through a [`ManagedFolderMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.managed_folders().list("bucket")
/// .prefix("At")
/// .page_token("dolores")
/// .page_size(-46)
/// .doit().await;
/// # }
/// ```
pub struct ManagedFolderListCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_prefix: Option<String>,
_page_token: Option<String>,
_page_size: Option<i32>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ManagedFolderListCall<'a, C> {}
impl<'a, C> ManagedFolderListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ManagedFolders)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.managedFolders.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "bucket", "prefix", "pageToken", "pageSize"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._prefix.as_ref() {
params.push("prefix", value);
}
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/managedFolders";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket containing the managed folder.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ManagedFolderListCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The managed folder name/path prefix to filter the output list of results.
///
/// Sets the *prefix* query property to the given value.
pub fn prefix(mut self, new_value: &str) -> ManagedFolderListCall<'a, C> {
self._prefix = Some(new_value.to_string());
self
}
/// A previously-returned page token representing part of the larger set of results to view.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ManagedFolderListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Maximum number of items to return in a single page of responses.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> ManagedFolderListCall<'a, C> {
self._page_size = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ManagedFolderListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ManagedFolderListCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ManagedFolderListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ManagedFolderListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ManagedFolderListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Updates an IAM policy for the specified managed folder.
///
/// A builder for the *setIamPolicy* method supported by a *managedFolder* resource.
/// It is not used directly, but through a [`ManagedFolderMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Policy;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Policy::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.managed_folders().set_iam_policy(req, "bucket", "managedFolder")
/// .user_project("aliquyam")
/// .doit().await;
/// # }
/// ```
pub struct ManagedFolderSetIamPolicyCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Policy,
_bucket: String,
_managed_folder: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ManagedFolderSetIamPolicyCall<'a, C> {}
impl<'a, C> ManagedFolderSetIamPolicyCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Policy)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.managedFolders.setIamPolicy",
http_method: hyper::Method::PUT,
});
for &field in ["alt", "bucket", "managedFolder", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("managedFolder", self._managed_folder);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/managedFolders/{managedFolder}/iam";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in
[("{bucket}", "bucket"), ("{managedFolder}", "managedFolder")].iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["managedFolder", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PUT)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Policy) -> ManagedFolderSetIamPolicyCall<'a, C> {
self._request = new_value;
self
}
/// Name of the bucket containing the managed folder.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ManagedFolderSetIamPolicyCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The managed folder name/path.
///
/// Sets the *managed folder* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn managed_folder(mut self, new_value: &str) -> ManagedFolderSetIamPolicyCall<'a, C> {
self._managed_folder = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ManagedFolderSetIamPolicyCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ManagedFolderSetIamPolicyCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ManagedFolderSetIamPolicyCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ManagedFolderSetIamPolicyCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ManagedFolderSetIamPolicyCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ManagedFolderSetIamPolicyCall<'a, C> {
self._scopes.clear();
self
}
}
/// Tests a set of permissions on the given managed folder to see which, if any, are held by the caller.
///
/// A builder for the *testIamPermissions* method supported by a *managedFolder* resource.
/// It is not used directly, but through a [`ManagedFolderMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.managed_folders().test_iam_permissions("bucket", "managedFolder", &vec!["ipsum".into()])
/// .user_project("Lorem")
/// .doit().await;
/// # }
/// ```
pub struct ManagedFolderTestIamPermissionCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_managed_folder: String,
_permissions: Vec<String>,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ManagedFolderTestIamPermissionCall<'a, C> {}
impl<'a, C> ManagedFolderTestIamPermissionCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, TestIamPermissionsResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.managedFolders.testIamPermissions",
http_method: hyper::Method::GET,
});
for &field in [
"alt",
"bucket",
"managedFolder",
"permissions",
"userProject",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("managedFolder", self._managed_folder);
if !self._permissions.is_empty() {
for f in self._permissions.iter() {
params.push("permissions", f);
}
}
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone()
+ "b/{bucket}/managedFolders/{managedFolder}/iam/testPermissions";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in
[("{bucket}", "bucket"), ("{managedFolder}", "managedFolder")].iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["managedFolder", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket containing the managed folder.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ManagedFolderTestIamPermissionCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The managed folder name/path.
///
/// Sets the *managed folder* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn managed_folder(mut self, new_value: &str) -> ManagedFolderTestIamPermissionCall<'a, C> {
self._managed_folder = new_value.to_string();
self
}
/// Permissions to test.
///
/// Append the given value to the *permissions* query property.
/// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn add_permissions(mut self, new_value: &str) -> ManagedFolderTestIamPermissionCall<'a, C> {
self._permissions.push(new_value.to_string());
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ManagedFolderTestIamPermissionCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ManagedFolderTestIamPermissionCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ManagedFolderTestIamPermissionCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ManagedFolderTestIamPermissionCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ManagedFolderTestIamPermissionCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ManagedFolderTestIamPermissionCall<'a, C> {
self._scopes.clear();
self
}
}
/// Permanently deletes a notification subscription.
///
/// A builder for the *delete* method supported by a *notification* resource.
/// It is not used directly, but through a [`NotificationMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.notifications().delete("bucket", "notification")
/// .user_project("sadipscing")
/// .doit().await;
/// # }
/// ```
pub struct NotificationDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_notification: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for NotificationDeleteCall<'a, C> {}
impl<'a, C> NotificationDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<common::Response> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.notifications.delete",
http_method: hyper::Method::DELETE,
});
for &field in ["bucket", "notification", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("notification", self._notification);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
let mut url = self.hub._base_url.clone() + "b/{bucket}/notificationConfigs/{notification}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in
[("{bucket}", "bucket"), ("{notification}", "notification")].iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["notification", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = common::Response::from_parts(parts, body);
dlg.finished(true);
return Ok(response);
}
}
}
}
/// The parent bucket of the notification.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> NotificationDeleteCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// ID of the notification to delete.
///
/// Sets the *notification* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn notification(mut self, new_value: &str) -> NotificationDeleteCall<'a, C> {
self._notification = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> NotificationDeleteCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> NotificationDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> NotificationDeleteCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> NotificationDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> NotificationDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> NotificationDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// View a notification configuration.
///
/// A builder for the *get* method supported by a *notification* resource.
/// It is not used directly, but through a [`NotificationMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.notifications().get("bucket", "notification")
/// .user_project("duo")
/// .doit().await;
/// # }
/// ```
pub struct NotificationGetCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_notification: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for NotificationGetCall<'a, C> {}
impl<'a, C> NotificationGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Notification)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.notifications.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "bucket", "notification", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("notification", self._notification);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/notificationConfigs/{notification}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in
[("{bucket}", "bucket"), ("{notification}", "notification")].iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["notification", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// The parent bucket of the notification.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> NotificationGetCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Notification ID
///
/// Sets the *notification* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn notification(mut self, new_value: &str) -> NotificationGetCall<'a, C> {
self._notification = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> NotificationGetCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> NotificationGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> NotificationGetCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> NotificationGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> NotificationGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> NotificationGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Creates a notification subscription for a given bucket.
///
/// A builder for the *insert* method supported by a *notification* resource.
/// It is not used directly, but through a [`NotificationMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Notification;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Notification::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.notifications().insert(req, "bucket")
/// .user_project("magna")
/// .doit().await;
/// # }
/// ```
pub struct NotificationInsertCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Notification,
_bucket: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for NotificationInsertCall<'a, C> {}
impl<'a, C> NotificationInsertCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Notification)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.notifications.insert",
http_method: hyper::Method::POST,
});
for &field in ["alt", "bucket", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/notificationConfigs";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Notification) -> NotificationInsertCall<'a, C> {
self._request = new_value;
self
}
/// The parent bucket of the notification.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> NotificationInsertCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> NotificationInsertCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> NotificationInsertCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> NotificationInsertCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> NotificationInsertCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> NotificationInsertCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> NotificationInsertCall<'a, C> {
self._scopes.clear();
self
}
}
/// Retrieves a list of notification subscriptions for a given bucket.
///
/// A builder for the *list* method supported by a *notification* resource.
/// It is not used directly, but through a [`NotificationMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.notifications().list("bucket")
/// .user_project("rebum.")
/// .doit().await;
/// # }
/// ```
pub struct NotificationListCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for NotificationListCall<'a, C> {}
impl<'a, C> NotificationListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Notifications)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.notifications.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "bucket", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/notificationConfigs";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a Google Cloud Storage bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> NotificationListCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> NotificationListCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> NotificationListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> NotificationListCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> NotificationListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> NotificationListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> NotificationListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Permanently deletes the ACL entry for the specified entity on the specified object.
///
/// A builder for the *delete* method supported by a *objectAccessControl* resource.
/// It is not used directly, but through a [`ObjectAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.object_access_controls().delete("bucket", "object", "entity")
/// .user_project("amet.")
/// .generation(-11)
/// .doit().await;
/// # }
/// ```
pub struct ObjectAccessControlDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_object: String,
_entity: String,
_user_project: Option<String>,
_generation: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectAccessControlDeleteCall<'a, C> {}
impl<'a, C> ObjectAccessControlDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<common::Response> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objectAccessControls.delete",
http_method: hyper::Method::DELETE,
});
for &field in ["bucket", "object", "entity", "userProject", "generation"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("object", self._object);
params.push("entity", self._entity);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._generation.as_ref() {
params.push("generation", value.to_string());
}
params.extend(self._additional_params.iter());
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/{object}/acl/{entity}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [
("{bucket}", "bucket"),
("{object}", "object"),
("{entity}", "entity"),
]
.iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["entity", "object", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = common::Response::from_parts(parts, body);
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectAccessControlDeleteCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn object(mut self, new_value: &str) -> ObjectAccessControlDeleteCall<'a, C> {
self._object = new_value.to_string();
self
}
/// The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
///
/// Sets the *entity* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn entity(mut self, new_value: &str) -> ObjectAccessControlDeleteCall<'a, C> {
self._entity = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectAccessControlDeleteCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If present, selects a specific revision of this object (as opposed to the latest version, the default).
///
/// Sets the *generation* query property to the given value.
pub fn generation(mut self, new_value: i64) -> ObjectAccessControlDeleteCall<'a, C> {
self._generation = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ObjectAccessControlDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectAccessControlDeleteCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectAccessControlDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectAccessControlDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectAccessControlDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Returns the ACL entry for the specified entity on the specified object.
///
/// A builder for the *get* method supported by a *objectAccessControl* resource.
/// It is not used directly, but through a [`ObjectAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.object_access_controls().get("bucket", "object", "entity")
/// .user_project("Lorem")
/// .generation(-58)
/// .doit().await;
/// # }
/// ```
pub struct ObjectAccessControlGetCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_object: String,
_entity: String,
_user_project: Option<String>,
_generation: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectAccessControlGetCall<'a, C> {}
impl<'a, C> ObjectAccessControlGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ObjectAccessControl)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objectAccessControls.get",
http_method: hyper::Method::GET,
});
for &field in [
"alt",
"bucket",
"object",
"entity",
"userProject",
"generation",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(7 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("object", self._object);
params.push("entity", self._entity);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._generation.as_ref() {
params.push("generation", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/{object}/acl/{entity}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [
("{bucket}", "bucket"),
("{object}", "object"),
("{entity}", "entity"),
]
.iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["entity", "object", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectAccessControlGetCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn object(mut self, new_value: &str) -> ObjectAccessControlGetCall<'a, C> {
self._object = new_value.to_string();
self
}
/// The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
///
/// Sets the *entity* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn entity(mut self, new_value: &str) -> ObjectAccessControlGetCall<'a, C> {
self._entity = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectAccessControlGetCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If present, selects a specific revision of this object (as opposed to the latest version, the default).
///
/// Sets the *generation* query property to the given value.
pub fn generation(mut self, new_value: i64) -> ObjectAccessControlGetCall<'a, C> {
self._generation = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ObjectAccessControlGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectAccessControlGetCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectAccessControlGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectAccessControlGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectAccessControlGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Creates a new ACL entry on the specified object.
///
/// A builder for the *insert* method supported by a *objectAccessControl* resource.
/// It is not used directly, but through a [`ObjectAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::ObjectAccessControl;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = ObjectAccessControl::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.object_access_controls().insert(req, "bucket", "object")
/// .user_project("tempor")
/// .generation(-34)
/// .doit().await;
/// # }
/// ```
pub struct ObjectAccessControlInsertCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: ObjectAccessControl,
_bucket: String,
_object: String,
_user_project: Option<String>,
_generation: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectAccessControlInsertCall<'a, C> {}
impl<'a, C> ObjectAccessControlInsertCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ObjectAccessControl)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objectAccessControls.insert",
http_method: hyper::Method::POST,
});
for &field in ["alt", "bucket", "object", "userProject", "generation"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(7 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("object", self._object);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._generation.as_ref() {
params.push("generation", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/{object}/acl";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{object}", "object")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["object", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: ObjectAccessControl,
) -> ObjectAccessControlInsertCall<'a, C> {
self._request = new_value;
self
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectAccessControlInsertCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn object(mut self, new_value: &str) -> ObjectAccessControlInsertCall<'a, C> {
self._object = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectAccessControlInsertCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If present, selects a specific revision of this object (as opposed to the latest version, the default).
///
/// Sets the *generation* query property to the given value.
pub fn generation(mut self, new_value: i64) -> ObjectAccessControlInsertCall<'a, C> {
self._generation = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ObjectAccessControlInsertCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectAccessControlInsertCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectAccessControlInsertCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectAccessControlInsertCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectAccessControlInsertCall<'a, C> {
self._scopes.clear();
self
}
}
/// Retrieves ACL entries on the specified object.
///
/// A builder for the *list* method supported by a *objectAccessControl* resource.
/// It is not used directly, but through a [`ObjectAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.object_access_controls().list("bucket", "object")
/// .user_project("dolore")
/// .generation(-97)
/// .doit().await;
/// # }
/// ```
pub struct ObjectAccessControlListCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_object: String,
_user_project: Option<String>,
_generation: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectAccessControlListCall<'a, C> {}
impl<'a, C> ObjectAccessControlListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ObjectAccessControls)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objectAccessControls.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "bucket", "object", "userProject", "generation"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("object", self._object);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._generation.as_ref() {
params.push("generation", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/{object}/acl";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{object}", "object")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["object", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectAccessControlListCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn object(mut self, new_value: &str) -> ObjectAccessControlListCall<'a, C> {
self._object = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectAccessControlListCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If present, selects a specific revision of this object (as opposed to the latest version, the default).
///
/// Sets the *generation* query property to the given value.
pub fn generation(mut self, new_value: i64) -> ObjectAccessControlListCall<'a, C> {
self._generation = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ObjectAccessControlListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectAccessControlListCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectAccessControlListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectAccessControlListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectAccessControlListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Patches an ACL entry on the specified object.
///
/// A builder for the *patch* method supported by a *objectAccessControl* resource.
/// It is not used directly, but through a [`ObjectAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::ObjectAccessControl;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = ObjectAccessControl::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.object_access_controls().patch(req, "bucket", "object", "entity")
/// .user_project("vero")
/// .generation(-20)
/// .doit().await;
/// # }
/// ```
pub struct ObjectAccessControlPatchCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: ObjectAccessControl,
_bucket: String,
_object: String,
_entity: String,
_user_project: Option<String>,
_generation: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectAccessControlPatchCall<'a, C> {}
impl<'a, C> ObjectAccessControlPatchCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ObjectAccessControl)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objectAccessControls.patch",
http_method: hyper::Method::PATCH,
});
for &field in [
"alt",
"bucket",
"object",
"entity",
"userProject",
"generation",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(8 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("object", self._object);
params.push("entity", self._entity);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._generation.as_ref() {
params.push("generation", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/{object}/acl/{entity}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [
("{bucket}", "bucket"),
("{object}", "object"),
("{entity}", "entity"),
]
.iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["entity", "object", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PATCH)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: ObjectAccessControl,
) -> ObjectAccessControlPatchCall<'a, C> {
self._request = new_value;
self
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectAccessControlPatchCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn object(mut self, new_value: &str) -> ObjectAccessControlPatchCall<'a, C> {
self._object = new_value.to_string();
self
}
/// The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
///
/// Sets the *entity* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn entity(mut self, new_value: &str) -> ObjectAccessControlPatchCall<'a, C> {
self._entity = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectAccessControlPatchCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If present, selects a specific revision of this object (as opposed to the latest version, the default).
///
/// Sets the *generation* query property to the given value.
pub fn generation(mut self, new_value: i64) -> ObjectAccessControlPatchCall<'a, C> {
self._generation = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ObjectAccessControlPatchCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectAccessControlPatchCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectAccessControlPatchCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectAccessControlPatchCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectAccessControlPatchCall<'a, C> {
self._scopes.clear();
self
}
}
/// Updates an ACL entry on the specified object.
///
/// A builder for the *update* method supported by a *objectAccessControl* resource.
/// It is not used directly, but through a [`ObjectAccessControlMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::ObjectAccessControl;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = ObjectAccessControl::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.object_access_controls().update(req, "bucket", "object", "entity")
/// .user_project("duo")
/// .generation(-63)
/// .doit().await;
/// # }
/// ```
pub struct ObjectAccessControlUpdateCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: ObjectAccessControl,
_bucket: String,
_object: String,
_entity: String,
_user_project: Option<String>,
_generation: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectAccessControlUpdateCall<'a, C> {}
impl<'a, C> ObjectAccessControlUpdateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ObjectAccessControl)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objectAccessControls.update",
http_method: hyper::Method::PUT,
});
for &field in [
"alt",
"bucket",
"object",
"entity",
"userProject",
"generation",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(8 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("object", self._object);
params.push("entity", self._entity);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._generation.as_ref() {
params.push("generation", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/{object}/acl/{entity}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [
("{bucket}", "bucket"),
("{object}", "object"),
("{entity}", "entity"),
]
.iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["entity", "object", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PUT)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: ObjectAccessControl,
) -> ObjectAccessControlUpdateCall<'a, C> {
self._request = new_value;
self
}
/// Name of a bucket.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectAccessControlUpdateCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn object(mut self, new_value: &str) -> ObjectAccessControlUpdateCall<'a, C> {
self._object = new_value.to_string();
self
}
/// The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
///
/// Sets the *entity* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn entity(mut self, new_value: &str) -> ObjectAccessControlUpdateCall<'a, C> {
self._entity = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectAccessControlUpdateCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If present, selects a specific revision of this object (as opposed to the latest version, the default).
///
/// Sets the *generation* query property to the given value.
pub fn generation(mut self, new_value: i64) -> ObjectAccessControlUpdateCall<'a, C> {
self._generation = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ObjectAccessControlUpdateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectAccessControlUpdateCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectAccessControlUpdateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectAccessControlUpdateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectAccessControlUpdateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Initiates a long-running bulk restore operation on the specified bucket.
///
/// A builder for the *bulkRestore* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::BulkRestoreObjectsRequest;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = BulkRestoreObjectsRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().bulk_restore(req, "bucket")
/// .doit().await;
/// # }
/// ```
pub struct ObjectBulkRestoreCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: BulkRestoreObjectsRequest,
_bucket: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectBulkRestoreCall<'a, C> {}
impl<'a, C> ObjectBulkRestoreCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, GoogleLongrunningOperation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.bulkRestore",
http_method: hyper::Method::POST,
});
for &field in ["alt", "bucket"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("bucket", self._bucket);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/bulkRestore";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: BulkRestoreObjectsRequest) -> ObjectBulkRestoreCall<'a, C> {
self._request = new_value;
self
}
/// Name of the bucket in which the object resides.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectBulkRestoreCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ObjectBulkRestoreCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectBulkRestoreCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectBulkRestoreCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectBulkRestoreCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectBulkRestoreCall<'a, C> {
self._scopes.clear();
self
}
}
/// Concatenates a list of existing objects into a new object in the same bucket.
///
/// A builder for the *compose* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::ComposeRequest;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = ComposeRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().compose(req, "destinationBucket", "destinationObject")
/// .user_project("et")
/// .kms_key_name("Lorem")
/// .if_metageneration_match(-33)
/// .if_generation_match(-59)
/// .destination_predefined_acl("rebum.")
/// .doit().await;
/// # }
/// ```
pub struct ObjectComposeCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: ComposeRequest,
_destination_bucket: String,
_destination_object: String,
_user_project: Option<String>,
_kms_key_name: Option<String>,
_if_metageneration_match: Option<i64>,
_if_generation_match: Option<i64>,
_destination_predefined_acl: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectComposeCall<'a, C> {}
impl<'a, C> ObjectComposeCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Object)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.compose",
http_method: hyper::Method::POST,
});
for &field in [
"alt",
"destinationBucket",
"destinationObject",
"userProject",
"kmsKeyName",
"ifMetagenerationMatch",
"ifGenerationMatch",
"destinationPredefinedAcl",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(10 + self._additional_params.len());
params.push("destinationBucket", self._destination_bucket);
params.push("destinationObject", self._destination_object);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._kms_key_name.as_ref() {
params.push("kmsKeyName", value);
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
if let Some(value) = self._if_generation_match.as_ref() {
params.push("ifGenerationMatch", value.to_string());
}
if let Some(value) = self._destination_predefined_acl.as_ref() {
params.push("destinationPredefinedAcl", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url =
self.hub._base_url.clone() + "b/{destinationBucket}/o/{destinationObject}/compose";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [
("{destinationBucket}", "destinationBucket"),
("{destinationObject}", "destinationObject"),
]
.iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["destinationObject", "destinationBucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: ComposeRequest) -> ObjectComposeCall<'a, C> {
self._request = new_value;
self
}
/// Name of the bucket containing the source objects. The destination object is stored in this bucket.
///
/// Sets the *destination bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn destination_bucket(mut self, new_value: &str) -> ObjectComposeCall<'a, C> {
self._destination_bucket = new_value.to_string();
self
}
/// Name of the new object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *destination object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn destination_object(mut self, new_value: &str) -> ObjectComposeCall<'a, C> {
self._destination_object = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectComposeCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// Resource name of the Cloud KMS key, of the form projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key, that will be used to encrypt the object. Overrides the object metadata's kms_key_name value, if any.
///
/// Sets the *kms key name* query property to the given value.
pub fn kms_key_name(mut self, new_value: &str) -> ObjectComposeCall<'a, C> {
self._kms_key_name = Some(new_value.to_string());
self
}
/// Makes the operation conditional on whether the object's current metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> ObjectComposeCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current generation matches the given value. Setting to 0 makes the operation succeed only if there are no live versions of the object.
///
/// Sets the *if generation match* query property to the given value.
pub fn if_generation_match(mut self, new_value: i64) -> ObjectComposeCall<'a, C> {
self._if_generation_match = Some(new_value);
self
}
/// Apply a predefined set of access controls to the destination object.
///
/// Sets the *destination predefined acl* query property to the given value.
pub fn destination_predefined_acl(mut self, new_value: &str) -> ObjectComposeCall<'a, C> {
self._destination_predefined_acl = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ObjectComposeCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectComposeCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectComposeCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectComposeCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectComposeCall<'a, C> {
self._scopes.clear();
self
}
}
/// Copies a source object to a destination object. Optionally overrides metadata.
///
/// A builder for the *copy* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Object;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Object::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().copy(req, "sourceBucket", "sourceObject", "destinationBucket", "destinationObject")
/// .user_project("aliquyam")
/// .source_generation(-37)
/// .projection("sit")
/// .if_source_metageneration_not_match(-26)
/// .if_source_metageneration_match(-16)
/// .if_source_generation_not_match(-19)
/// .if_source_generation_match(-96)
/// .if_metageneration_not_match(-19)
/// .if_metageneration_match(-30)
/// .if_generation_not_match(-38)
/// .if_generation_match(-64)
/// .destination_predefined_acl("dolor")
/// .destination_kms_key_name("aliquyam")
/// .doit().await;
/// # }
/// ```
pub struct ObjectCopyCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Object,
_source_bucket: String,
_source_object: String,
_destination_bucket: String,
_destination_object: String,
_user_project: Option<String>,
_source_generation: Option<i64>,
_projection: Option<String>,
_if_source_metageneration_not_match: Option<i64>,
_if_source_metageneration_match: Option<i64>,
_if_source_generation_not_match: Option<i64>,
_if_source_generation_match: Option<i64>,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_if_generation_not_match: Option<i64>,
_if_generation_match: Option<i64>,
_destination_predefined_acl: Option<String>,
_destination_kms_key_name: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectCopyCall<'a, C> {}
impl<'a, C> ObjectCopyCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Object)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.copy",
http_method: hyper::Method::POST,
});
for &field in [
"alt",
"sourceBucket",
"sourceObject",
"destinationBucket",
"destinationObject",
"userProject",
"sourceGeneration",
"projection",
"ifSourceMetagenerationNotMatch",
"ifSourceMetagenerationMatch",
"ifSourceGenerationNotMatch",
"ifSourceGenerationMatch",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
"ifGenerationNotMatch",
"ifGenerationMatch",
"destinationPredefinedAcl",
"destinationKmsKeyName",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(20 + self._additional_params.len());
params.push("sourceBucket", self._source_bucket);
params.push("sourceObject", self._source_object);
params.push("destinationBucket", self._destination_bucket);
params.push("destinationObject", self._destination_object);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._source_generation.as_ref() {
params.push("sourceGeneration", value.to_string());
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._if_source_metageneration_not_match.as_ref() {
params.push("ifSourceMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_source_metageneration_match.as_ref() {
params.push("ifSourceMetagenerationMatch", value.to_string());
}
if let Some(value) = self._if_source_generation_not_match.as_ref() {
params.push("ifSourceGenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_source_generation_match.as_ref() {
params.push("ifSourceGenerationMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
if let Some(value) = self._if_generation_not_match.as_ref() {
params.push("ifGenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_generation_match.as_ref() {
params.push("ifGenerationMatch", value.to_string());
}
if let Some(value) = self._destination_predefined_acl.as_ref() {
params.push("destinationPredefinedAcl", value);
}
if let Some(value) = self._destination_kms_key_name.as_ref() {
params.push("destinationKmsKeyName", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{sourceBucket}/o/{sourceObject}/copyTo/b/{destinationBucket}/o/{destinationObject}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [
("{sourceBucket}", "sourceBucket"),
("{sourceObject}", "sourceObject"),
("{destinationBucket}", "destinationBucket"),
("{destinationObject}", "destinationObject"),
]
.iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = [
"destinationObject",
"destinationBucket",
"sourceObject",
"sourceBucket",
];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Object) -> ObjectCopyCall<'a, C> {
self._request = new_value;
self
}
/// Name of the bucket in which to find the source object.
///
/// Sets the *source bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn source_bucket(mut self, new_value: &str) -> ObjectCopyCall<'a, C> {
self._source_bucket = new_value.to_string();
self
}
/// Name of the source object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *source object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn source_object(mut self, new_value: &str) -> ObjectCopyCall<'a, C> {
self._source_object = new_value.to_string();
self
}
/// Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *destination bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn destination_bucket(mut self, new_value: &str) -> ObjectCopyCall<'a, C> {
self._destination_bucket = new_value.to_string();
self
}
/// Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any.
///
/// Sets the *destination object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn destination_object(mut self, new_value: &str) -> ObjectCopyCall<'a, C> {
self._destination_object = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectCopyCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If present, selects a specific revision of the source object (as opposed to the latest version, the default).
///
/// Sets the *source generation* query property to the given value.
pub fn source_generation(mut self, new_value: i64) -> ObjectCopyCall<'a, C> {
self._source_generation = Some(new_value);
self
}
/// Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> ObjectCopyCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// Makes the operation conditional on whether the source object's current metageneration does not match the given value.
///
/// Sets the *if source metageneration not match* query property to the given value.
pub fn if_source_metageneration_not_match(mut self, new_value: i64) -> ObjectCopyCall<'a, C> {
self._if_source_metageneration_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the source object's current metageneration matches the given value.
///
/// Sets the *if source metageneration match* query property to the given value.
pub fn if_source_metageneration_match(mut self, new_value: i64) -> ObjectCopyCall<'a, C> {
self._if_source_metageneration_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the source object's current generation does not match the given value.
///
/// Sets the *if source generation not match* query property to the given value.
pub fn if_source_generation_not_match(mut self, new_value: i64) -> ObjectCopyCall<'a, C> {
self._if_source_generation_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the source object's current generation matches the given value.
///
/// Sets the *if source generation match* query property to the given value.
pub fn if_source_generation_match(mut self, new_value: i64) -> ObjectCopyCall<'a, C> {
self._if_source_generation_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the destination object's current metageneration does not match the given value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> ObjectCopyCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the destination object's current metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> ObjectCopyCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the destination object's current generation does not match the given value. If no live object exists, the precondition fails. Setting to 0 makes the operation succeed only if there is a live version of the object.
///
/// Sets the *if generation not match* query property to the given value.
pub fn if_generation_not_match(mut self, new_value: i64) -> ObjectCopyCall<'a, C> {
self._if_generation_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the destination object's current generation matches the given value. Setting to 0 makes the operation succeed only if there are no live versions of the object.
///
/// Sets the *if generation match* query property to the given value.
pub fn if_generation_match(mut self, new_value: i64) -> ObjectCopyCall<'a, C> {
self._if_generation_match = Some(new_value);
self
}
/// Apply a predefined set of access controls to the destination object.
///
/// Sets the *destination predefined acl* query property to the given value.
pub fn destination_predefined_acl(mut self, new_value: &str) -> ObjectCopyCall<'a, C> {
self._destination_predefined_acl = Some(new_value.to_string());
self
}
/// Resource name of the Cloud KMS key, of the form projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key, that will be used to encrypt the object. Overrides the object metadata's kms_key_name value, if any.
///
/// Sets the *destination kms key name* query property to the given value.
pub fn destination_kms_key_name(mut self, new_value: &str) -> ObjectCopyCall<'a, C> {
self._destination_kms_key_name = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ObjectCopyCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectCopyCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectCopyCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectCopyCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectCopyCall<'a, C> {
self._scopes.clear();
self
}
}
/// Deletes an object and its metadata. Deletions are permanent if versioning is not enabled for the bucket, or if the generation parameter is used.
///
/// A builder for the *delete* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().delete("bucket", "object")
/// .user_project("nonumy")
/// .if_metageneration_not_match(-18)
/// .if_metageneration_match(-8)
/// .if_generation_not_match(-23)
/// .if_generation_match(-39)
/// .generation(-43)
/// .doit().await;
/// # }
/// ```
pub struct ObjectDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_object: String,
_user_project: Option<String>,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_if_generation_not_match: Option<i64>,
_if_generation_match: Option<i64>,
_generation: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectDeleteCall<'a, C> {}
impl<'a, C> ObjectDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<common::Response> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.delete",
http_method: hyper::Method::DELETE,
});
for &field in [
"bucket",
"object",
"userProject",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
"ifGenerationNotMatch",
"ifGenerationMatch",
"generation",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(9 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("object", self._object);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
if let Some(value) = self._if_generation_not_match.as_ref() {
params.push("ifGenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_generation_match.as_ref() {
params.push("ifGenerationMatch", value.to_string());
}
if let Some(value) = self._generation.as_ref() {
params.push("generation", value.to_string());
}
params.extend(self._additional_params.iter());
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/{object}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{object}", "object")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["object", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = common::Response::from_parts(parts, body);
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket in which the object resides.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectDeleteCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn object(mut self, new_value: &str) -> ObjectDeleteCall<'a, C> {
self._object = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectDeleteCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// Makes the operation conditional on whether the object's current metageneration does not match the given value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> ObjectDeleteCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> ObjectDeleteCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current generation does not match the given value. If no live object exists, the precondition fails. Setting to 0 makes the operation succeed only if there is a live version of the object.
///
/// Sets the *if generation not match* query property to the given value.
pub fn if_generation_not_match(mut self, new_value: i64) -> ObjectDeleteCall<'a, C> {
self._if_generation_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current generation matches the given value. Setting to 0 makes the operation succeed only if there are no live versions of the object.
///
/// Sets the *if generation match* query property to the given value.
pub fn if_generation_match(mut self, new_value: i64) -> ObjectDeleteCall<'a, C> {
self._if_generation_match = Some(new_value);
self
}
/// If present, permanently deletes a specific revision of this object (as opposed to the latest version, the default).
///
/// Sets the *generation* query property to the given value.
pub fn generation(mut self, new_value: i64) -> ObjectDeleteCall<'a, C> {
self._generation = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ObjectDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectDeleteCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Retrieves an object or its metadata.
///
/// This method supports **media download**. To enable it, adjust the builder like this:
/// `.param("alt", "media")`.
/// Please note that due to missing multi-part support on the server side, you will only receive the media,
/// but not the `Object` structure that you would usually get. The latter will be a default value.
///
/// A builder for the *get* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().get("bucket", "object")
/// .user_project("dolor")
/// .soft_deleted(false)
/// .restore_token("At")
/// .projection("erat")
/// .if_metageneration_not_match(-71)
/// .if_metageneration_match(-5)
/// .if_generation_not_match(-73)
/// .if_generation_match(-19)
/// .generation(-96)
/// .doit().await;
/// # }
/// ```
pub struct ObjectGetCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_object: String,
_user_project: Option<String>,
_soft_deleted: Option<bool>,
_restore_token: Option<String>,
_projection: Option<String>,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_if_generation_not_match: Option<i64>,
_if_generation_match: Option<i64>,
_generation: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectGetCall<'a, C> {}
impl<'a, C> ObjectGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Object)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.get",
http_method: hyper::Method::GET,
});
for &field in [
"bucket",
"object",
"userProject",
"softDeleted",
"restoreToken",
"projection",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
"ifGenerationNotMatch",
"ifGenerationMatch",
"generation",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(12 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("object", self._object);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._soft_deleted.as_ref() {
params.push("softDeleted", value.to_string());
}
if let Some(value) = self._restore_token.as_ref() {
params.push("restoreToken", value);
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
if let Some(value) = self._if_generation_not_match.as_ref() {
params.push("ifGenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_generation_match.as_ref() {
params.push("ifGenerationMatch", value.to_string());
}
if let Some(value) = self._generation.as_ref() {
params.push("generation", value.to_string());
}
params.extend(self._additional_params.iter());
let (alt_field_missing, enable_resource_parsing) = {
if let Some(value) = params.get("alt") {
(false, value == "json")
} else {
(true, true)
}
};
if alt_field_missing {
params.push("alt", "json");
}
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/{object}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{object}", "object")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["object", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = if enable_resource_parsing {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
} else {
(
common::Response::from_parts(parts, body),
Default::default(),
)
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket in which the object resides.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectGetCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn object(mut self, new_value: &str) -> ObjectGetCall<'a, C> {
self._object = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectGetCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If true, only soft-deleted object versions will be listed. The default is false. For more information, see [Soft Delete](https://cloud.google.com/storage/docs/soft-delete).
///
/// Sets the *soft deleted* query property to the given value.
pub fn soft_deleted(mut self, new_value: bool) -> ObjectGetCall<'a, C> {
self._soft_deleted = Some(new_value);
self
}
/// Restore token used to differentiate soft-deleted objects with the same name and generation. Only applicable for hierarchical namespace buckets and if softDeleted is set to true. This parameter is optional, and is only required in the rare case when there are multiple soft-deleted objects with the same name and generation.
///
/// Sets the *restore token* query property to the given value.
pub fn restore_token(mut self, new_value: &str) -> ObjectGetCall<'a, C> {
self._restore_token = Some(new_value.to_string());
self
}
/// Set of properties to return. Defaults to noAcl.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> ObjectGetCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// Makes the operation conditional on whether the object's current metageneration does not match the given value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> ObjectGetCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> ObjectGetCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current generation does not match the given value. If no live object exists, the precondition fails. Setting to 0 makes the operation succeed only if there is a live version of the object.
///
/// Sets the *if generation not match* query property to the given value.
pub fn if_generation_not_match(mut self, new_value: i64) -> ObjectGetCall<'a, C> {
self._if_generation_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current generation matches the given value. Setting to 0 makes the operation succeed only if there are no live versions of the object.
///
/// Sets the *if generation match* query property to the given value.
pub fn if_generation_match(mut self, new_value: i64) -> ObjectGetCall<'a, C> {
self._if_generation_match = Some(new_value);
self
}
/// If present, selects a specific revision of this object (as opposed to the latest version, the default).
///
/// Sets the *generation* query property to the given value.
pub fn generation(mut self, new_value: i64) -> ObjectGetCall<'a, C> {
self._generation = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ObjectGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectGetCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Returns an IAM policy for the specified object.
///
/// A builder for the *getIamPolicy* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().get_iam_policy("bucket", "object")
/// .user_project("sadipscing")
/// .generation(-42)
/// .doit().await;
/// # }
/// ```
pub struct ObjectGetIamPolicyCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_object: String,
_user_project: Option<String>,
_generation: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectGetIamPolicyCall<'a, C> {}
impl<'a, C> ObjectGetIamPolicyCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Policy)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.getIamPolicy",
http_method: hyper::Method::GET,
});
for &field in ["alt", "bucket", "object", "userProject", "generation"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("object", self._object);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._generation.as_ref() {
params.push("generation", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/{object}/iam";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{object}", "object")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["object", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket in which the object resides.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectGetIamPolicyCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn object(mut self, new_value: &str) -> ObjectGetIamPolicyCall<'a, C> {
self._object = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectGetIamPolicyCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If present, selects a specific revision of this object (as opposed to the latest version, the default).
///
/// Sets the *generation* query property to the given value.
pub fn generation(mut self, new_value: i64) -> ObjectGetIamPolicyCall<'a, C> {
self._generation = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ObjectGetIamPolicyCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectGetIamPolicyCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectGetIamPolicyCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectGetIamPolicyCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectGetIamPolicyCall<'a, C> {
self._scopes.clear();
self
}
}
/// Stores a new object and metadata.
///
/// A builder for the *insert* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Object;
/// use std::fs;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Object::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `upload_resumable(...)`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().insert(req, "bucket")
/// .user_project("ipsum")
/// .projection("Stet")
/// .predefined_acl("gubergren")
/// .name("ipsum")
/// .kms_key_name("no")
/// .if_metageneration_not_match(-98)
/// .if_metageneration_match(-13)
/// .if_generation_not_match(-47)
/// .if_generation_match(-56)
/// .content_encoding("justo")
/// .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()).await;
/// # }
/// ```
pub struct ObjectInsertCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Object,
_bucket: String,
_user_project: Option<String>,
_projection: Option<String>,
_predefined_acl: Option<String>,
_name: Option<String>,
_kms_key_name: Option<String>,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_if_generation_not_match: Option<i64>,
_if_generation_match: Option<i64>,
_content_encoding: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectInsertCall<'a, C> {}
impl<'a, C> ObjectInsertCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
async fn doit<RS>(
mut self,
mut reader: RS,
reader_mime_type: mime::Mime,
protocol: common::UploadProtocol,
) -> common::Result<(common::Response, Object)>
where
RS: common::ReadSeek,
{
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.insert",
http_method: hyper::Method::POST,
});
for &field in [
"alt",
"bucket",
"userProject",
"projection",
"predefinedAcl",
"name",
"kmsKeyName",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
"ifGenerationNotMatch",
"ifGenerationMatch",
"contentEncoding",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(14 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._predefined_acl.as_ref() {
params.push("predefinedAcl", value);
}
if let Some(value) = self._name.as_ref() {
params.push("name", value);
}
if let Some(value) = self._kms_key_name.as_ref() {
params.push("kmsKeyName", value);
}
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
if let Some(value) = self._if_generation_not_match.as_ref() {
params.push("ifGenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_generation_match.as_ref() {
params.push("ifGenerationMatch", value.to_string());
}
if let Some(value) = self._content_encoding.as_ref() {
params.push("contentEncoding", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let (mut url, upload_type) = if protocol == common::UploadProtocol::Resumable {
(
self.hub._root_url.clone() + "resumable/upload/storage/v1/b/{bucket}/o",
"resumable",
)
} else if protocol == common::UploadProtocol::Simple {
(
self.hub._root_url.clone() + "upload/storage/v1/b/{bucket}/o",
"multipart",
)
} else {
unreachable!()
};
params.push("uploadType", upload_type);
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut upload_url_from_server;
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let mut mp_reader: common::MultiPartReader = Default::default();
let (mut body_reader, content_type) = match protocol {
common::UploadProtocol::Simple => {
mp_reader.reserve_exact(2);
let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
reader.seek(std::io::SeekFrom::Start(0)).unwrap();
mp_reader
.add_part(
&mut request_value_reader,
request_size,
json_mime_type.clone(),
)
.add_part(&mut reader, size, reader_mime_type.clone());
(
&mut mp_reader as &mut (dyn std::io::Read + Send),
common::MultiPartReader::mime_type(),
)
}
_ => (
&mut request_value_reader as &mut (dyn std::io::Read + Send),
json_mime_type.clone(),
),
};
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
upload_url_from_server = true;
if protocol == common::UploadProtocol::Resumable {
req_builder = req_builder
.header("X-Upload-Content-Type", format!("{}", reader_mime_type));
}
let mut body_reader_bytes = vec![];
body_reader.read_to_end(&mut body_reader_bytes).unwrap();
let request = req_builder
.header(CONTENT_TYPE, content_type.to_string())
.body(common::to_body(body_reader_bytes.into()));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
if protocol == common::UploadProtocol::Resumable {
let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
reader.seek(std::io::SeekFrom::Start(0)).unwrap();
let upload_result = {
let url_str = &parts
.headers
.get("Location")
.expect("LOCATION header is part of protocol")
.to_str()
.unwrap();
if upload_url_from_server {
dlg.store_upload_url(Some(url_str));
}
common::ResumableUploadHelper {
client: &self.hub.client,
delegate: dlg,
start_at: if upload_url_from_server {
Some(0)
} else {
None
},
auth: &self.hub.auth,
user_agent: &self.hub._user_agent,
// TODO: Check this assumption
auth_header: format!(
"Bearer {}",
token
.ok_or_else(|| common::Error::MissingToken(
"resumable upload requires token".into()
))?
.as_str()
),
url: url_str,
reader: &mut reader,
media_type: reader_mime_type.clone(),
content_length: size,
}
.upload()
.await
};
match upload_result {
None => {
dlg.finished(false);
return Err(common::Error::Cancelled);
}
Some(Err(err)) => {
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Some(Ok(response)) => {
(parts, body) = response.into_parts();
if !parts.status.is_success() {
dlg.store_upload_url(None);
dlg.finished(false);
return Err(common::Error::Failure(
common::Response::from_parts(parts, body),
));
}
}
}
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Upload media in a resumable fashion.
/// Even if the upload fails or is interrupted, it can be resumed for a
/// certain amount of time as the server maintains state temporarily.
///
/// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL
/// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate
/// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using
/// `cancel_chunk_upload(...)`.
///
/// * *multipart*: yes
/// * *max size*: 0kb
/// * *valid mime types*: '*/*'
pub async fn upload_resumable<RS>(
self,
resumeable_stream: RS,
mime_type: mime::Mime,
) -> common::Result<(common::Response, Object)>
where
RS: common::ReadSeek,
{
self.doit(
resumeable_stream,
mime_type,
common::UploadProtocol::Resumable,
)
.await
}
/// Upload media all at once.
/// If the upload fails for whichever reason, all progress is lost.
///
/// * *multipart*: yes
/// * *max size*: 0kb
/// * *valid mime types*: '*/*'
pub async fn upload<RS>(
self,
stream: RS,
mime_type: mime::Mime,
) -> common::Result<(common::Response, Object)>
where
RS: common::ReadSeek,
{
self.doit(stream, mime_type, common::UploadProtocol::Simple)
.await
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Object) -> ObjectInsertCall<'a, C> {
self._request = new_value;
self
}
/// Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectInsertCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectInsertCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> ObjectInsertCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// Apply a predefined set of access controls to this object.
///
/// Sets the *predefined acl* query property to the given value.
pub fn predefined_acl(mut self, new_value: &str) -> ObjectInsertCall<'a, C> {
self._predefined_acl = Some(new_value.to_string());
self
}
/// Name of the object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *name* query property to the given value.
pub fn name(mut self, new_value: &str) -> ObjectInsertCall<'a, C> {
self._name = Some(new_value.to_string());
self
}
/// Resource name of the Cloud KMS key, of the form projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key, that will be used to encrypt the object. Overrides the object metadata's kms_key_name value, if any.
///
/// Sets the *kms key name* query property to the given value.
pub fn kms_key_name(mut self, new_value: &str) -> ObjectInsertCall<'a, C> {
self._kms_key_name = Some(new_value.to_string());
self
}
/// Makes the operation conditional on whether the object's current metageneration does not match the given value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> ObjectInsertCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> ObjectInsertCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current generation does not match the given value. If no live object exists, the precondition fails. Setting to 0 makes the operation succeed only if there is a live version of the object.
///
/// Sets the *if generation not match* query property to the given value.
pub fn if_generation_not_match(mut self, new_value: i64) -> ObjectInsertCall<'a, C> {
self._if_generation_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current generation matches the given value. Setting to 0 makes the operation succeed only if there are no live versions of the object.
///
/// Sets the *if generation match* query property to the given value.
pub fn if_generation_match(mut self, new_value: i64) -> ObjectInsertCall<'a, C> {
self._if_generation_match = Some(new_value);
self
}
/// If set, sets the contentEncoding property of the final object to this value. Setting this parameter is equivalent to setting the contentEncoding metadata property. This can be useful when uploading an object with uploadType=media to indicate the encoding of the content being uploaded.
///
/// Sets the *content encoding* query property to the given value.
pub fn content_encoding(mut self, new_value: &str) -> ObjectInsertCall<'a, C> {
self._content_encoding = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ObjectInsertCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectInsertCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectInsertCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectInsertCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectInsertCall<'a, C> {
self._scopes.clear();
self
}
}
/// Retrieves a list of objects matching the criteria.
///
/// A builder for the *list* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().list("bucket")
/// .versions(false)
/// .user_project("nonumy")
/// .start_offset("sea")
/// .soft_deleted(false)
/// .projection("kasd")
/// .prefix("justo")
/// .page_token("ea")
/// .max_results(24)
/// .match_glob("erat")
/// .include_trailing_delimiter(false)
/// .include_folders_as_prefixes(false)
/// .filter("nonumy")
/// .end_offset("erat")
/// .delimiter("erat")
/// .doit().await;
/// # }
/// ```
pub struct ObjectListCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_versions: Option<bool>,
_user_project: Option<String>,
_start_offset: Option<String>,
_soft_deleted: Option<bool>,
_projection: Option<String>,
_prefix: Option<String>,
_page_token: Option<String>,
_max_results: Option<u32>,
_match_glob: Option<String>,
_include_trailing_delimiter: Option<bool>,
_include_folders_as_prefixes: Option<bool>,
_filter: Option<String>,
_end_offset: Option<String>,
_delimiter: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectListCall<'a, C> {}
impl<'a, C> ObjectListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Objects)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.list",
http_method: hyper::Method::GET,
});
for &field in [
"alt",
"bucket",
"versions",
"userProject",
"startOffset",
"softDeleted",
"projection",
"prefix",
"pageToken",
"maxResults",
"matchGlob",
"includeTrailingDelimiter",
"includeFoldersAsPrefixes",
"filter",
"endOffset",
"delimiter",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(17 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._versions.as_ref() {
params.push("versions", value.to_string());
}
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._start_offset.as_ref() {
params.push("startOffset", value);
}
if let Some(value) = self._soft_deleted.as_ref() {
params.push("softDeleted", value.to_string());
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._prefix.as_ref() {
params.push("prefix", value);
}
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._max_results.as_ref() {
params.push("maxResults", value.to_string());
}
if let Some(value) = self._match_glob.as_ref() {
params.push("matchGlob", value);
}
if let Some(value) = self._include_trailing_delimiter.as_ref() {
params.push("includeTrailingDelimiter", value.to_string());
}
if let Some(value) = self._include_folders_as_prefixes.as_ref() {
params.push("includeFoldersAsPrefixes", value.to_string());
}
if let Some(value) = self._filter.as_ref() {
params.push("filter", value);
}
if let Some(value) = self._end_offset.as_ref() {
params.push("endOffset", value);
}
if let Some(value) = self._delimiter.as_ref() {
params.push("delimiter", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/o";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket in which to look for objects.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectListCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// If true, lists all versions of an object as distinct results. The default is false. For more information, see [Object Versioning](https://cloud.google.com/storage/docs/object-versioning).
///
/// Sets the *versions* query property to the given value.
pub fn versions(mut self, new_value: bool) -> ObjectListCall<'a, C> {
self._versions = Some(new_value);
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectListCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// Filter results to objects whose names are lexicographically equal to or after startOffset. If endOffset is also set, the objects listed will have names between startOffset (inclusive) and endOffset (exclusive).
///
/// Sets the *start offset* query property to the given value.
pub fn start_offset(mut self, new_value: &str) -> ObjectListCall<'a, C> {
self._start_offset = Some(new_value.to_string());
self
}
/// If true, only soft-deleted object versions will be listed. The default is false. For more information, see [Soft Delete](https://cloud.google.com/storage/docs/soft-delete).
///
/// Sets the *soft deleted* query property to the given value.
pub fn soft_deleted(mut self, new_value: bool) -> ObjectListCall<'a, C> {
self._soft_deleted = Some(new_value);
self
}
/// Set of properties to return. Defaults to noAcl.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> ObjectListCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// Filter results to objects whose names begin with this prefix.
///
/// Sets the *prefix* query property to the given value.
pub fn prefix(mut self, new_value: &str) -> ObjectListCall<'a, C> {
self._prefix = Some(new_value.to_string());
self
}
/// A previously-returned page token representing part of the larger set of results to view.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ObjectListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Maximum number of items plus prefixes to return in a single page of responses. As duplicate prefixes are omitted, fewer total results may be returned than requested. The service will use this parameter or 1,000 items, whichever is smaller.
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: u32) -> ObjectListCall<'a, C> {
self._max_results = Some(new_value);
self
}
/// Filter results to objects and prefixes that match this glob pattern.
///
/// Sets the *match glob* query property to the given value.
pub fn match_glob(mut self, new_value: &str) -> ObjectListCall<'a, C> {
self._match_glob = Some(new_value.to_string());
self
}
/// If true, objects that end in exactly one instance of delimiter will have their metadata included in items in addition to prefixes.
///
/// Sets the *include trailing delimiter* query property to the given value.
pub fn include_trailing_delimiter(mut self, new_value: bool) -> ObjectListCall<'a, C> {
self._include_trailing_delimiter = Some(new_value);
self
}
/// Only applicable if delimiter is set to '/'. If true, will also include folders and managed folders (besides objects) in the returned prefixes.
///
/// Sets the *include folders as prefixes* query property to the given value.
pub fn include_folders_as_prefixes(mut self, new_value: bool) -> ObjectListCall<'a, C> {
self._include_folders_as_prefixes = Some(new_value);
self
}
/// Filter the returned objects. Currently only supported for the contexts field. If delimiter is set, the returned prefixes are exempt from this filter.
///
/// Sets the *filter* query property to the given value.
pub fn filter(mut self, new_value: &str) -> ObjectListCall<'a, C> {
self._filter = Some(new_value.to_string());
self
}
/// Filter results to objects whose names are lexicographically before endOffset. If startOffset is also set, the objects listed will have names between startOffset (inclusive) and endOffset (exclusive).
///
/// Sets the *end offset* query property to the given value.
pub fn end_offset(mut self, new_value: &str) -> ObjectListCall<'a, C> {
self._end_offset = Some(new_value.to_string());
self
}
/// Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted.
///
/// Sets the *delimiter* query property to the given value.
pub fn delimiter(mut self, new_value: &str) -> ObjectListCall<'a, C> {
self._delimiter = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ObjectListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectListCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Moves the source object to the destination object in the same bucket.
///
/// A builder for the *move* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().move_("bucket", "sourceObject", "destinationObject")
/// .user_project("eos")
/// .projection("duo")
/// .if_source_metageneration_not_match(-94)
/// .if_source_metageneration_match(-46)
/// .if_source_generation_not_match(-72)
/// .if_source_generation_match(-14)
/// .if_metageneration_not_match(-1)
/// .if_metageneration_match(-48)
/// .if_generation_not_match(-59)
/// .if_generation_match(-31)
/// .doit().await;
/// # }
/// ```
pub struct ObjectMoveCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_source_object: String,
_destination_object: String,
_user_project: Option<String>,
_projection: Option<String>,
_if_source_metageneration_not_match: Option<i64>,
_if_source_metageneration_match: Option<i64>,
_if_source_generation_not_match: Option<i64>,
_if_source_generation_match: Option<i64>,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_if_generation_not_match: Option<i64>,
_if_generation_match: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectMoveCall<'a, C> {}
impl<'a, C> ObjectMoveCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Object)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.move",
http_method: hyper::Method::POST,
});
for &field in [
"alt",
"bucket",
"sourceObject",
"destinationObject",
"userProject",
"projection",
"ifSourceMetagenerationNotMatch",
"ifSourceMetagenerationMatch",
"ifSourceGenerationNotMatch",
"ifSourceGenerationMatch",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
"ifGenerationNotMatch",
"ifGenerationMatch",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(15 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("sourceObject", self._source_object);
params.push("destinationObject", self._destination_object);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._if_source_metageneration_not_match.as_ref() {
params.push("ifSourceMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_source_metageneration_match.as_ref() {
params.push("ifSourceMetagenerationMatch", value.to_string());
}
if let Some(value) = self._if_source_generation_not_match.as_ref() {
params.push("ifSourceGenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_source_generation_match.as_ref() {
params.push("ifSourceGenerationMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
if let Some(value) = self._if_generation_not_match.as_ref() {
params.push("ifGenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_generation_match.as_ref() {
params.push("ifGenerationMatch", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url =
self.hub._base_url.clone() + "b/{bucket}/o/{sourceObject}/moveTo/o/{destinationObject}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [
("{bucket}", "bucket"),
("{sourceObject}", "sourceObject"),
("{destinationObject}", "destinationObject"),
]
.iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["destinationObject", "sourceObject", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket in which the object resides.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectMoveCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the source object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *source object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn source_object(mut self, new_value: &str) -> ObjectMoveCall<'a, C> {
self._source_object = new_value.to_string();
self
}
/// Name of the destination object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *destination object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn destination_object(mut self, new_value: &str) -> ObjectMoveCall<'a, C> {
self._destination_object = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectMoveCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// Set of properties to return. Defaults to noAcl.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> ObjectMoveCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// Makes the operation conditional on whether the source object's current metageneration does not match the given value. `ifSourceMetagenerationMatch` and `ifSourceMetagenerationNotMatch` conditions are mutually exclusive: it's an error for both of them to be set in the request.
///
/// Sets the *if source metageneration not match* query property to the given value.
pub fn if_source_metageneration_not_match(mut self, new_value: i64) -> ObjectMoveCall<'a, C> {
self._if_source_metageneration_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the source object's current metageneration matches the given value. `ifSourceMetagenerationMatch` and `ifSourceMetagenerationNotMatch` conditions are mutually exclusive: it's an error for both of them to be set in the request.
///
/// Sets the *if source metageneration match* query property to the given value.
pub fn if_source_metageneration_match(mut self, new_value: i64) -> ObjectMoveCall<'a, C> {
self._if_source_metageneration_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the source object's current generation does not match the given value. `ifSourceGenerationMatch` and `ifSourceGenerationNotMatch` conditions are mutually exclusive: it's an error for both of them to be set in the request.
///
/// Sets the *if source generation not match* query property to the given value.
pub fn if_source_generation_not_match(mut self, new_value: i64) -> ObjectMoveCall<'a, C> {
self._if_source_generation_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the source object's current generation matches the given value. `ifSourceGenerationMatch` and `ifSourceGenerationNotMatch` conditions are mutually exclusive: it's an error for both of them to be set in the request.
///
/// Sets the *if source generation match* query property to the given value.
pub fn if_source_generation_match(mut self, new_value: i64) -> ObjectMoveCall<'a, C> {
self._if_source_generation_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the destination object's current metageneration does not match the given value. `ifMetagenerationMatch` and `ifMetagenerationNotMatch` conditions are mutually exclusive: it's an error for both of them to be set in the request.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> ObjectMoveCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the destination object's current metageneration matches the given value. `ifMetagenerationMatch` and `ifMetagenerationNotMatch` conditions are mutually exclusive: it's an error for both of them to be set in the request.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> ObjectMoveCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the destination object's current generation does not match the given value. If no live object exists, the precondition fails. Setting to 0 makes the operation succeed only if there is a live version of the object.`ifGenerationMatch` and `ifGenerationNotMatch` conditions are mutually exclusive: it's an error for both of them to be set in the request.
///
/// Sets the *if generation not match* query property to the given value.
pub fn if_generation_not_match(mut self, new_value: i64) -> ObjectMoveCall<'a, C> {
self._if_generation_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the destination object's current generation matches the given value. Setting to 0 makes the operation succeed only if there are no live versions of the object. `ifGenerationMatch` and `ifGenerationNotMatch` conditions are mutually exclusive: it's an error for both of them to be set in the request.
///
/// Sets the *if generation match* query property to the given value.
pub fn if_generation_match(mut self, new_value: i64) -> ObjectMoveCall<'a, C> {
self._if_generation_match = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ObjectMoveCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectMoveCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectMoveCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectMoveCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectMoveCall<'a, C> {
self._scopes.clear();
self
}
}
/// Patches an object's metadata.
///
/// A builder for the *patch* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Object;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Object::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().patch(req, "bucket", "object")
/// .user_project("Lorem")
/// .projection("At")
/// .predefined_acl("diam")
/// .override_unlocked_retention(false)
/// .if_metageneration_not_match(-93)
/// .if_metageneration_match(-18)
/// .if_generation_not_match(-17)
/// .if_generation_match(-84)
/// .generation(-55)
/// .doit().await;
/// # }
/// ```
pub struct ObjectPatchCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Object,
_bucket: String,
_object: String,
_user_project: Option<String>,
_projection: Option<String>,
_predefined_acl: Option<String>,
_override_unlocked_retention: Option<bool>,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_if_generation_not_match: Option<i64>,
_if_generation_match: Option<i64>,
_generation: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectPatchCall<'a, C> {}
impl<'a, C> ObjectPatchCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Object)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.patch",
http_method: hyper::Method::PATCH,
});
for &field in [
"alt",
"bucket",
"object",
"userProject",
"projection",
"predefinedAcl",
"overrideUnlockedRetention",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
"ifGenerationNotMatch",
"ifGenerationMatch",
"generation",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(14 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("object", self._object);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._predefined_acl.as_ref() {
params.push("predefinedAcl", value);
}
if let Some(value) = self._override_unlocked_retention.as_ref() {
params.push("overrideUnlockedRetention", value.to_string());
}
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
if let Some(value) = self._if_generation_not_match.as_ref() {
params.push("ifGenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_generation_match.as_ref() {
params.push("ifGenerationMatch", value.to_string());
}
if let Some(value) = self._generation.as_ref() {
params.push("generation", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/{object}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{object}", "object")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["object", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PATCH)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Object) -> ObjectPatchCall<'a, C> {
self._request = new_value;
self
}
/// Name of the bucket in which the object resides.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectPatchCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn object(mut self, new_value: &str) -> ObjectPatchCall<'a, C> {
self._object = new_value.to_string();
self
}
/// The project to be billed for this request, for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectPatchCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// Set of properties to return. Defaults to full.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> ObjectPatchCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// Apply a predefined set of access controls to this object.
///
/// Sets the *predefined acl* query property to the given value.
pub fn predefined_acl(mut self, new_value: &str) -> ObjectPatchCall<'a, C> {
self._predefined_acl = Some(new_value.to_string());
self
}
/// Must be true to remove the retention configuration, reduce its unlocked retention period, or change its mode from unlocked to locked.
///
/// Sets the *override unlocked retention* query property to the given value.
pub fn override_unlocked_retention(mut self, new_value: bool) -> ObjectPatchCall<'a, C> {
self._override_unlocked_retention = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current metageneration does not match the given value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> ObjectPatchCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> ObjectPatchCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current generation does not match the given value. If no live object exists, the precondition fails. Setting to 0 makes the operation succeed only if there is a live version of the object.
///
/// Sets the *if generation not match* query property to the given value.
pub fn if_generation_not_match(mut self, new_value: i64) -> ObjectPatchCall<'a, C> {
self._if_generation_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current generation matches the given value. Setting to 0 makes the operation succeed only if there are no live versions of the object.
///
/// Sets the *if generation match* query property to the given value.
pub fn if_generation_match(mut self, new_value: i64) -> ObjectPatchCall<'a, C> {
self._if_generation_match = Some(new_value);
self
}
/// If present, selects a specific revision of this object (as opposed to the latest version, the default).
///
/// Sets the *generation* query property to the given value.
pub fn generation(mut self, new_value: i64) -> ObjectPatchCall<'a, C> {
self._generation = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ObjectPatchCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectPatchCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectPatchCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectPatchCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectPatchCall<'a, C> {
self._scopes.clear();
self
}
}
/// Restores a soft-deleted object.
///
/// A builder for the *restore* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().restore("bucket", "object", -53)
/// .user_project("sit")
/// .restore_token("Lorem")
/// .projection("Stet")
/// .if_metageneration_not_match(-70)
/// .if_metageneration_match(-94)
/// .if_generation_not_match(-32)
/// .if_generation_match(-31)
/// .copy_source_acl(false)
/// .doit().await;
/// # }
/// ```
pub struct ObjectRestoreCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_object: String,
_generation: i64,
_user_project: Option<String>,
_restore_token: Option<String>,
_projection: Option<String>,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_if_generation_not_match: Option<i64>,
_if_generation_match: Option<i64>,
_copy_source_acl: Option<bool>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectRestoreCall<'a, C> {}
impl<'a, C> ObjectRestoreCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Object)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.restore",
http_method: hyper::Method::POST,
});
for &field in [
"alt",
"bucket",
"object",
"generation",
"userProject",
"restoreToken",
"projection",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
"ifGenerationNotMatch",
"ifGenerationMatch",
"copySourceAcl",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(13 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("object", self._object);
params.push("generation", self._generation.to_string());
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._restore_token.as_ref() {
params.push("restoreToken", value);
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
if let Some(value) = self._if_generation_not_match.as_ref() {
params.push("ifGenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_generation_match.as_ref() {
params.push("ifGenerationMatch", value.to_string());
}
if let Some(value) = self._copy_source_acl.as_ref() {
params.push("copySourceAcl", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/{object}/restore";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{object}", "object")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["object", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket in which the object resides.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectRestoreCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn object(mut self, new_value: &str) -> ObjectRestoreCall<'a, C> {
self._object = new_value.to_string();
self
}
/// Selects a specific revision of this object.
///
/// Sets the *generation* query property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn generation(mut self, new_value: i64) -> ObjectRestoreCall<'a, C> {
self._generation = new_value;
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectRestoreCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// Restore token used to differentiate sof-deleted objects with the same name and generation. Only applicable for hierarchical namespace buckets. This parameter is optional, and is only required in the rare case when there are multiple soft-deleted objects with the same name and generation.
///
/// Sets the *restore token* query property to the given value.
pub fn restore_token(mut self, new_value: &str) -> ObjectRestoreCall<'a, C> {
self._restore_token = Some(new_value.to_string());
self
}
/// Set of properties to return. Defaults to full.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> ObjectRestoreCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// Makes the operation conditional on whether none of the object's live metagenerations match the given value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> ObjectRestoreCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's one live metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> ObjectRestoreCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// Makes the operation conditional on whether none of the object's live generations match the given value. If no live object exists, the precondition fails. Setting to 0 makes the operation succeed only if there is a live version of the object.
///
/// Sets the *if generation not match* query property to the given value.
pub fn if_generation_not_match(mut self, new_value: i64) -> ObjectRestoreCall<'a, C> {
self._if_generation_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's one live generation matches the given value. Setting to 0 makes the operation succeed only if there are no live versions of the object.
///
/// Sets the *if generation match* query property to the given value.
pub fn if_generation_match(mut self, new_value: i64) -> ObjectRestoreCall<'a, C> {
self._if_generation_match = Some(new_value);
self
}
/// If true, copies the source object's ACL; otherwise, uses the bucket's default object ACL. The default is false.
///
/// Sets the *copy source acl* query property to the given value.
pub fn copy_source_acl(mut self, new_value: bool) -> ObjectRestoreCall<'a, C> {
self._copy_source_acl = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ObjectRestoreCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectRestoreCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectRestoreCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectRestoreCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectRestoreCall<'a, C> {
self._scopes.clear();
self
}
}
/// Rewrites a source object to a destination object. Optionally overrides metadata.
///
/// A builder for the *rewrite* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Object;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Object::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().rewrite(req, "sourceBucket", "sourceObject", "destinationBucket", "destinationObject")
/// .user_project("sed")
/// .source_generation(-65)
/// .rewrite_token("aliquyam")
/// .projection("kasd")
/// .max_bytes_rewritten_per_call(-101)
/// .if_source_metageneration_not_match(-48)
/// .if_source_metageneration_match(-63)
/// .if_source_generation_not_match(-39)
/// .if_source_generation_match(-54)
/// .if_metageneration_not_match(-97)
/// .if_metageneration_match(-3)
/// .if_generation_not_match(-16)
/// .if_generation_match(-60)
/// .destination_predefined_acl("ipsum")
/// .destination_kms_key_name("ipsum")
/// .doit().await;
/// # }
/// ```
pub struct ObjectRewriteCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Object,
_source_bucket: String,
_source_object: String,
_destination_bucket: String,
_destination_object: String,
_user_project: Option<String>,
_source_generation: Option<i64>,
_rewrite_token: Option<String>,
_projection: Option<String>,
_max_bytes_rewritten_per_call: Option<i64>,
_if_source_metageneration_not_match: Option<i64>,
_if_source_metageneration_match: Option<i64>,
_if_source_generation_not_match: Option<i64>,
_if_source_generation_match: Option<i64>,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_if_generation_not_match: Option<i64>,
_if_generation_match: Option<i64>,
_destination_predefined_acl: Option<String>,
_destination_kms_key_name: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectRewriteCall<'a, C> {}
impl<'a, C> ObjectRewriteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, RewriteResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.rewrite",
http_method: hyper::Method::POST,
});
for &field in [
"alt",
"sourceBucket",
"sourceObject",
"destinationBucket",
"destinationObject",
"userProject",
"sourceGeneration",
"rewriteToken",
"projection",
"maxBytesRewrittenPerCall",
"ifSourceMetagenerationNotMatch",
"ifSourceMetagenerationMatch",
"ifSourceGenerationNotMatch",
"ifSourceGenerationMatch",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
"ifGenerationNotMatch",
"ifGenerationMatch",
"destinationPredefinedAcl",
"destinationKmsKeyName",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(22 + self._additional_params.len());
params.push("sourceBucket", self._source_bucket);
params.push("sourceObject", self._source_object);
params.push("destinationBucket", self._destination_bucket);
params.push("destinationObject", self._destination_object);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._source_generation.as_ref() {
params.push("sourceGeneration", value.to_string());
}
if let Some(value) = self._rewrite_token.as_ref() {
params.push("rewriteToken", value);
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._max_bytes_rewritten_per_call.as_ref() {
params.push("maxBytesRewrittenPerCall", value.to_string());
}
if let Some(value) = self._if_source_metageneration_not_match.as_ref() {
params.push("ifSourceMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_source_metageneration_match.as_ref() {
params.push("ifSourceMetagenerationMatch", value.to_string());
}
if let Some(value) = self._if_source_generation_not_match.as_ref() {
params.push("ifSourceGenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_source_generation_match.as_ref() {
params.push("ifSourceGenerationMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
if let Some(value) = self._if_generation_not_match.as_ref() {
params.push("ifGenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_generation_match.as_ref() {
params.push("ifGenerationMatch", value.to_string());
}
if let Some(value) = self._destination_predefined_acl.as_ref() {
params.push("destinationPredefinedAcl", value);
}
if let Some(value) = self._destination_kms_key_name.as_ref() {
params.push("destinationKmsKeyName", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{sourceBucket}/o/{sourceObject}/rewriteTo/b/{destinationBucket}/o/{destinationObject}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [
("{sourceBucket}", "sourceBucket"),
("{sourceObject}", "sourceObject"),
("{destinationBucket}", "destinationBucket"),
("{destinationObject}", "destinationObject"),
]
.iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = [
"destinationObject",
"destinationBucket",
"sourceObject",
"sourceBucket",
];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Object) -> ObjectRewriteCall<'a, C> {
self._request = new_value;
self
}
/// Name of the bucket in which to find the source object.
///
/// Sets the *source bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn source_bucket(mut self, new_value: &str) -> ObjectRewriteCall<'a, C> {
self._source_bucket = new_value.to_string();
self
}
/// Name of the source object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *source object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn source_object(mut self, new_value: &str) -> ObjectRewriteCall<'a, C> {
self._source_object = new_value.to_string();
self
}
/// Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.
///
/// Sets the *destination bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn destination_bucket(mut self, new_value: &str) -> ObjectRewriteCall<'a, C> {
self._destination_bucket = new_value.to_string();
self
}
/// Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *destination object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn destination_object(mut self, new_value: &str) -> ObjectRewriteCall<'a, C> {
self._destination_object = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectRewriteCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If present, selects a specific revision of the source object (as opposed to the latest version, the default).
///
/// Sets the *source generation* query property to the given value.
pub fn source_generation(mut self, new_value: i64) -> ObjectRewriteCall<'a, C> {
self._source_generation = Some(new_value);
self
}
/// Include this field (from the previous rewrite response) on each rewrite request after the first one, until the rewrite response 'done' flag is true. Calls that provide a rewriteToken can omit all other request fields, but if included those fields must match the values provided in the first rewrite request.
///
/// Sets the *rewrite token* query property to the given value.
pub fn rewrite_token(mut self, new_value: &str) -> ObjectRewriteCall<'a, C> {
self._rewrite_token = Some(new_value.to_string());
self
}
/// Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> ObjectRewriteCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// The maximum number of bytes that will be rewritten per rewrite request. Most callers shouldn't need to specify this parameter - it is primarily in place to support testing. If specified the value must be an integral multiple of 1 MiB (1048576). Also, this only applies to requests where the source and destination span locations and/or storage classes. Finally, this value must not change across rewrite calls else you'll get an error that the rewriteToken is invalid.
///
/// Sets the *max bytes rewritten per call* query property to the given value.
pub fn max_bytes_rewritten_per_call(mut self, new_value: i64) -> ObjectRewriteCall<'a, C> {
self._max_bytes_rewritten_per_call = Some(new_value);
self
}
/// Makes the operation conditional on whether the source object's current metageneration does not match the given value.
///
/// Sets the *if source metageneration not match* query property to the given value.
pub fn if_source_metageneration_not_match(
mut self,
new_value: i64,
) -> ObjectRewriteCall<'a, C> {
self._if_source_metageneration_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the source object's current metageneration matches the given value.
///
/// Sets the *if source metageneration match* query property to the given value.
pub fn if_source_metageneration_match(mut self, new_value: i64) -> ObjectRewriteCall<'a, C> {
self._if_source_metageneration_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the source object's current generation does not match the given value.
///
/// Sets the *if source generation not match* query property to the given value.
pub fn if_source_generation_not_match(mut self, new_value: i64) -> ObjectRewriteCall<'a, C> {
self._if_source_generation_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the source object's current generation matches the given value.
///
/// Sets the *if source generation match* query property to the given value.
pub fn if_source_generation_match(mut self, new_value: i64) -> ObjectRewriteCall<'a, C> {
self._if_source_generation_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the destination object's current metageneration does not match the given value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> ObjectRewriteCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the destination object's current metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> ObjectRewriteCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current generation does not match the given value. If no live object exists, the precondition fails. Setting to 0 makes the operation succeed only if there is a live version of the object.
///
/// Sets the *if generation not match* query property to the given value.
pub fn if_generation_not_match(mut self, new_value: i64) -> ObjectRewriteCall<'a, C> {
self._if_generation_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current generation matches the given value. Setting to 0 makes the operation succeed only if there are no live versions of the object.
///
/// Sets the *if generation match* query property to the given value.
pub fn if_generation_match(mut self, new_value: i64) -> ObjectRewriteCall<'a, C> {
self._if_generation_match = Some(new_value);
self
}
/// Apply a predefined set of access controls to the destination object.
///
/// Sets the *destination predefined acl* query property to the given value.
pub fn destination_predefined_acl(mut self, new_value: &str) -> ObjectRewriteCall<'a, C> {
self._destination_predefined_acl = Some(new_value.to_string());
self
}
/// Resource name of the Cloud KMS key, of the form projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key, that will be used to encrypt the object. Overrides the object metadata's kms_key_name value, if any.
///
/// Sets the *destination kms key name* query property to the given value.
pub fn destination_kms_key_name(mut self, new_value: &str) -> ObjectRewriteCall<'a, C> {
self._destination_kms_key_name = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ObjectRewriteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectRewriteCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectRewriteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectRewriteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectRewriteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Updates an IAM policy for the specified object.
///
/// A builder for the *setIamPolicy* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Policy;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Policy::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().set_iam_policy(req, "bucket", "object")
/// .user_project("eirmod")
/// .generation(-4)
/// .doit().await;
/// # }
/// ```
pub struct ObjectSetIamPolicyCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Policy,
_bucket: String,
_object: String,
_user_project: Option<String>,
_generation: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectSetIamPolicyCall<'a, C> {}
impl<'a, C> ObjectSetIamPolicyCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Policy)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.setIamPolicy",
http_method: hyper::Method::PUT,
});
for &field in ["alt", "bucket", "object", "userProject", "generation"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(7 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("object", self._object);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._generation.as_ref() {
params.push("generation", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/{object}/iam";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{object}", "object")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["object", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PUT)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Policy) -> ObjectSetIamPolicyCall<'a, C> {
self._request = new_value;
self
}
/// Name of the bucket in which the object resides.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectSetIamPolicyCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn object(mut self, new_value: &str) -> ObjectSetIamPolicyCall<'a, C> {
self._object = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectSetIamPolicyCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If present, selects a specific revision of this object (as opposed to the latest version, the default).
///
/// Sets the *generation* query property to the given value.
pub fn generation(mut self, new_value: i64) -> ObjectSetIamPolicyCall<'a, C> {
self._generation = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ObjectSetIamPolicyCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectSetIamPolicyCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectSetIamPolicyCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectSetIamPolicyCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectSetIamPolicyCall<'a, C> {
self._scopes.clear();
self
}
}
/// Tests a set of permissions on the given object to see which, if any, are held by the caller.
///
/// A builder for the *testIamPermissions* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().test_iam_permissions("bucket", "object", &vec!["dolor".into()])
/// .user_project("consetetur")
/// .generation(-22)
/// .doit().await;
/// # }
/// ```
pub struct ObjectTestIamPermissionCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_bucket: String,
_object: String,
_permissions: Vec<String>,
_user_project: Option<String>,
_generation: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectTestIamPermissionCall<'a, C> {}
impl<'a, C> ObjectTestIamPermissionCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, TestIamPermissionsResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.testIamPermissions",
http_method: hyper::Method::GET,
});
for &field in [
"alt",
"bucket",
"object",
"permissions",
"userProject",
"generation",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(7 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("object", self._object);
if !self._permissions.is_empty() {
for f in self._permissions.iter() {
params.push("permissions", f);
}
}
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._generation.as_ref() {
params.push("generation", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/{object}/iam/testPermissions";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{object}", "object")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["object", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the bucket in which the object resides.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectTestIamPermissionCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn object(mut self, new_value: &str) -> ObjectTestIamPermissionCall<'a, C> {
self._object = new_value.to_string();
self
}
/// Permissions to test.
///
/// Append the given value to the *permissions* query property.
/// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn add_permissions(mut self, new_value: &str) -> ObjectTestIamPermissionCall<'a, C> {
self._permissions.push(new_value.to_string());
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectTestIamPermissionCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// If present, selects a specific revision of this object (as opposed to the latest version, the default).
///
/// Sets the *generation* query property to the given value.
pub fn generation(mut self, new_value: i64) -> ObjectTestIamPermissionCall<'a, C> {
self._generation = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ObjectTestIamPermissionCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectTestIamPermissionCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectTestIamPermissionCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectTestIamPermissionCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectTestIamPermissionCall<'a, C> {
self._scopes.clear();
self
}
}
/// Updates an object's metadata.
///
/// A builder for the *update* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Object;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Object::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().update(req, "bucket", "object")
/// .user_project("nonumy")
/// .projection("diam")
/// .predefined_acl("ipsum")
/// .override_unlocked_retention(true)
/// .if_metageneration_not_match(-15)
/// .if_metageneration_match(-78)
/// .if_generation_not_match(-77)
/// .if_generation_match(-92)
/// .generation(-47)
/// .doit().await;
/// # }
/// ```
pub struct ObjectUpdateCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Object,
_bucket: String,
_object: String,
_user_project: Option<String>,
_projection: Option<String>,
_predefined_acl: Option<String>,
_override_unlocked_retention: Option<bool>,
_if_metageneration_not_match: Option<i64>,
_if_metageneration_match: Option<i64>,
_if_generation_not_match: Option<i64>,
_if_generation_match: Option<i64>,
_generation: Option<i64>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectUpdateCall<'a, C> {}
impl<'a, C> ObjectUpdateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Object)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.update",
http_method: hyper::Method::PUT,
});
for &field in [
"alt",
"bucket",
"object",
"userProject",
"projection",
"predefinedAcl",
"overrideUnlockedRetention",
"ifMetagenerationNotMatch",
"ifMetagenerationMatch",
"ifGenerationNotMatch",
"ifGenerationMatch",
"generation",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(14 + self._additional_params.len());
params.push("bucket", self._bucket);
params.push("object", self._object);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._predefined_acl.as_ref() {
params.push("predefinedAcl", value);
}
if let Some(value) = self._override_unlocked_retention.as_ref() {
params.push("overrideUnlockedRetention", value.to_string());
}
if let Some(value) = self._if_metageneration_not_match.as_ref() {
params.push("ifMetagenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_metageneration_match.as_ref() {
params.push("ifMetagenerationMatch", value.to_string());
}
if let Some(value) = self._if_generation_not_match.as_ref() {
params.push("ifGenerationNotMatch", value.to_string());
}
if let Some(value) = self._if_generation_match.as_ref() {
params.push("ifGenerationMatch", value.to_string());
}
if let Some(value) = self._generation.as_ref() {
params.push("generation", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/{object}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket"), ("{object}", "object")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["object", "bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PUT)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Object) -> ObjectUpdateCall<'a, C> {
self._request = new_value;
self
}
/// Name of the bucket in which the object resides.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectUpdateCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// Name of the object. For information about how to URL encode object names to be path safe, see [Encoding URI Path Parts](https://cloud.google.com/storage/docs/request-endpoints#encoding).
///
/// Sets the *object* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn object(mut self, new_value: &str) -> ObjectUpdateCall<'a, C> {
self._object = new_value.to_string();
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectUpdateCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// Set of properties to return. Defaults to full.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> ObjectUpdateCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// Apply a predefined set of access controls to this object.
///
/// Sets the *predefined acl* query property to the given value.
pub fn predefined_acl(mut self, new_value: &str) -> ObjectUpdateCall<'a, C> {
self._predefined_acl = Some(new_value.to_string());
self
}
/// Must be true to remove the retention configuration, reduce its unlocked retention period, or change its mode from unlocked to locked.
///
/// Sets the *override unlocked retention* query property to the given value.
pub fn override_unlocked_retention(mut self, new_value: bool) -> ObjectUpdateCall<'a, C> {
self._override_unlocked_retention = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current metageneration does not match the given value.
///
/// Sets the *if metageneration not match* query property to the given value.
pub fn if_metageneration_not_match(mut self, new_value: i64) -> ObjectUpdateCall<'a, C> {
self._if_metageneration_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current metageneration matches the given value.
///
/// Sets the *if metageneration match* query property to the given value.
pub fn if_metageneration_match(mut self, new_value: i64) -> ObjectUpdateCall<'a, C> {
self._if_metageneration_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current generation does not match the given value. If no live object exists, the precondition fails. Setting to 0 makes the operation succeed only if there is a live version of the object.
///
/// Sets the *if generation not match* query property to the given value.
pub fn if_generation_not_match(mut self, new_value: i64) -> ObjectUpdateCall<'a, C> {
self._if_generation_not_match = Some(new_value);
self
}
/// Makes the operation conditional on whether the object's current generation matches the given value. Setting to 0 makes the operation succeed only if there are no live versions of the object.
///
/// Sets the *if generation match* query property to the given value.
pub fn if_generation_match(mut self, new_value: i64) -> ObjectUpdateCall<'a, C> {
self._if_generation_match = Some(new_value);
self
}
/// If present, selects a specific revision of this object (as opposed to the latest version, the default).
///
/// Sets the *generation* query property to the given value.
pub fn generation(mut self, new_value: i64) -> ObjectUpdateCall<'a, C> {
self._generation = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> ObjectUpdateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectUpdateCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectUpdateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectUpdateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectUpdateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Watch for changes on all objects in a bucket.
///
/// A builder for the *watchAll* method supported by a *object* resource.
/// It is not used directly, but through a [`ObjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::Channel;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Channel::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.objects().watch_all(req, "bucket")
/// .versions(false)
/// .user_project("erat")
/// .start_offset("duo")
/// .projection("et")
/// .prefix("erat")
/// .page_token("sit")
/// .max_results(28)
/// .include_trailing_delimiter(false)
/// .end_offset("accusam")
/// .delimiter("ut")
/// .doit().await;
/// # }
/// ```
pub struct ObjectWatchAllCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: Channel,
_bucket: String,
_versions: Option<bool>,
_user_project: Option<String>,
_start_offset: Option<String>,
_projection: Option<String>,
_prefix: Option<String>,
_page_token: Option<String>,
_max_results: Option<u32>,
_include_trailing_delimiter: Option<bool>,
_end_offset: Option<String>,
_delimiter: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ObjectWatchAllCall<'a, C> {}
impl<'a, C> ObjectWatchAllCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Channel)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.objects.watchAll",
http_method: hyper::Method::POST,
});
for &field in [
"alt",
"bucket",
"versions",
"userProject",
"startOffset",
"projection",
"prefix",
"pageToken",
"maxResults",
"includeTrailingDelimiter",
"endOffset",
"delimiter",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(14 + self._additional_params.len());
params.push("bucket", self._bucket);
if let Some(value) = self._versions.as_ref() {
params.push("versions", value.to_string());
}
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._start_offset.as_ref() {
params.push("startOffset", value);
}
if let Some(value) = self._projection.as_ref() {
params.push("projection", value);
}
if let Some(value) = self._prefix.as_ref() {
params.push("prefix", value);
}
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._max_results.as_ref() {
params.push("maxResults", value.to_string());
}
if let Some(value) = self._include_trailing_delimiter.as_ref() {
params.push("includeTrailingDelimiter", value.to_string());
}
if let Some(value) = self._end_offset.as_ref() {
params.push("endOffset", value);
}
if let Some(value) = self._delimiter.as_ref() {
params.push("delimiter", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "b/{bucket}/o/watch";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{bucket}", "bucket")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["bucket"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Channel) -> ObjectWatchAllCall<'a, C> {
self._request = new_value;
self
}
/// Name of the bucket in which to look for objects.
///
/// Sets the *bucket* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn bucket(mut self, new_value: &str) -> ObjectWatchAllCall<'a, C> {
self._bucket = new_value.to_string();
self
}
/// If true, lists all versions of an object as distinct results. The default is false. For more information, see [Object Versioning](https://cloud.google.com/storage/docs/object-versioning).
///
/// Sets the *versions* query property to the given value.
pub fn versions(mut self, new_value: bool) -> ObjectWatchAllCall<'a, C> {
self._versions = Some(new_value);
self
}
/// The project to be billed for this request. Required for Requester Pays buckets.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ObjectWatchAllCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// Filter results to objects whose names are lexicographically equal to or after startOffset. If endOffset is also set, the objects listed will have names between startOffset (inclusive) and endOffset (exclusive).
///
/// Sets the *start offset* query property to the given value.
pub fn start_offset(mut self, new_value: &str) -> ObjectWatchAllCall<'a, C> {
self._start_offset = Some(new_value.to_string());
self
}
/// Set of properties to return. Defaults to noAcl.
///
/// Sets the *projection* query property to the given value.
pub fn projection(mut self, new_value: &str) -> ObjectWatchAllCall<'a, C> {
self._projection = Some(new_value.to_string());
self
}
/// Filter results to objects whose names begin with this prefix.
///
/// Sets the *prefix* query property to the given value.
pub fn prefix(mut self, new_value: &str) -> ObjectWatchAllCall<'a, C> {
self._prefix = Some(new_value.to_string());
self
}
/// A previously-returned page token representing part of the larger set of results to view.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ObjectWatchAllCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Maximum number of items plus prefixes to return in a single page of responses. As duplicate prefixes are omitted, fewer total results may be returned than requested. The service will use this parameter or 1,000 items, whichever is smaller.
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: u32) -> ObjectWatchAllCall<'a, C> {
self._max_results = Some(new_value);
self
}
/// If true, objects that end in exactly one instance of delimiter will have their metadata included in items in addition to prefixes.
///
/// Sets the *include trailing delimiter* query property to the given value.
pub fn include_trailing_delimiter(mut self, new_value: bool) -> ObjectWatchAllCall<'a, C> {
self._include_trailing_delimiter = Some(new_value);
self
}
/// Filter results to objects whose names are lexicographically before endOffset. If startOffset is also set, the objects listed will have names between startOffset (inclusive) and endOffset (exclusive).
///
/// Sets the *end offset* query property to the given value.
pub fn end_offset(mut self, new_value: &str) -> ObjectWatchAllCall<'a, C> {
self._end_offset = Some(new_value.to_string());
self
}
/// Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted.
///
/// Sets the *delimiter* query property to the given value.
pub fn delimiter(mut self, new_value: &str) -> ObjectWatchAllCall<'a, C> {
self._delimiter = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ObjectWatchAllCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ObjectWatchAllCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ObjectWatchAllCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ObjectWatchAllCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ObjectWatchAllCall<'a, C> {
self._scopes.clear();
self
}
}
/// Creates a new HMAC key for the specified service account.
///
/// A builder for the *hmacKeys.create* method supported by a *project* resource.
/// It is not used directly, but through a [`ProjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.projects().hmac_keys_create("projectId", "serviceAccountEmail")
/// .user_project("dolor")
/// .doit().await;
/// # }
/// ```
pub struct ProjectHmacKeyCreateCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_project_id: String,
_service_account_email: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectHmacKeyCreateCall<'a, C> {}
impl<'a, C> ProjectHmacKeyCreateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, HmacKey)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.projects.hmacKeys.create",
http_method: hyper::Method::POST,
});
for &field in ["alt", "projectId", "serviceAccountEmail", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("projectId", self._project_id);
params.push("serviceAccountEmail", self._service_account_email);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "projects/{projectId}/hmacKeys";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{projectId}", "projectId")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["projectId"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Project ID owning the service account.
///
/// Sets the *project id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project_id(mut self, new_value: &str) -> ProjectHmacKeyCreateCall<'a, C> {
self._project_id = new_value.to_string();
self
}
/// Email address of the service account.
///
/// Sets the *service account email* query property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn service_account_email(mut self, new_value: &str) -> ProjectHmacKeyCreateCall<'a, C> {
self._service_account_email = new_value.to_string();
self
}
/// The project to be billed for this request.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ProjectHmacKeyCreateCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ProjectHmacKeyCreateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ProjectHmacKeyCreateCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectHmacKeyCreateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectHmacKeyCreateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectHmacKeyCreateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Deletes an HMAC key.
///
/// A builder for the *hmacKeys.delete* method supported by a *project* resource.
/// It is not used directly, but through a [`ProjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.projects().hmac_keys_delete("projectId", "accessId")
/// .user_project("aliquyam")
/// .doit().await;
/// # }
/// ```
pub struct ProjectHmacKeyDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_project_id: String,
_access_id: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectHmacKeyDeleteCall<'a, C> {}
impl<'a, C> ProjectHmacKeyDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<common::Response> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.projects.hmacKeys.delete",
http_method: hyper::Method::DELETE,
});
for &field in ["projectId", "accessId", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("projectId", self._project_id);
params.push("accessId", self._access_id);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
let mut url = self.hub._base_url.clone() + "projects/{projectId}/hmacKeys/{accessId}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadWrite.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in
[("{projectId}", "projectId"), ("{accessId}", "accessId")].iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["accessId", "projectId"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = common::Response::from_parts(parts, body);
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Project ID owning the requested key
///
/// Sets the *project id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project_id(mut self, new_value: &str) -> ProjectHmacKeyDeleteCall<'a, C> {
self._project_id = new_value.to_string();
self
}
/// Name of the HMAC key to be deleted.
///
/// Sets the *access id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn access_id(mut self, new_value: &str) -> ProjectHmacKeyDeleteCall<'a, C> {
self._access_id = new_value.to_string();
self
}
/// The project to be billed for this request.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ProjectHmacKeyDeleteCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ProjectHmacKeyDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ProjectHmacKeyDeleteCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadWrite`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectHmacKeyDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectHmacKeyDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectHmacKeyDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Retrieves an HMAC key's metadata
///
/// A builder for the *hmacKeys.get* method supported by a *project* resource.
/// It is not used directly, but through a [`ProjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.projects().hmac_keys_get("projectId", "accessId")
/// .user_project("invidunt")
/// .doit().await;
/// # }
/// ```
pub struct ProjectHmacKeyGetCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_project_id: String,
_access_id: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectHmacKeyGetCall<'a, C> {}
impl<'a, C> ProjectHmacKeyGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, HmacKeyMetadata)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.projects.hmacKeys.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "projectId", "accessId", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("projectId", self._project_id);
params.push("accessId", self._access_id);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "projects/{projectId}/hmacKeys/{accessId}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in
[("{projectId}", "projectId"), ("{accessId}", "accessId")].iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["accessId", "projectId"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Project ID owning the service account of the requested key.
///
/// Sets the *project id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project_id(mut self, new_value: &str) -> ProjectHmacKeyGetCall<'a, C> {
self._project_id = new_value.to_string();
self
}
/// Name of the HMAC key.
///
/// Sets the *access id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn access_id(mut self, new_value: &str) -> ProjectHmacKeyGetCall<'a, C> {
self._access_id = new_value.to_string();
self
}
/// The project to be billed for this request.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ProjectHmacKeyGetCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ProjectHmacKeyGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ProjectHmacKeyGetCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectHmacKeyGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectHmacKeyGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectHmacKeyGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Retrieves a list of HMAC keys matching the criteria.
///
/// A builder for the *hmacKeys.list* method supported by a *project* resource.
/// It is not used directly, but through a [`ProjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.projects().hmac_keys_list("projectId")
/// .user_project("duo")
/// .show_deleted_keys(true)
/// .service_account_email("Stet")
/// .page_token("sadipscing")
/// .max_results(90)
/// .doit().await;
/// # }
/// ```
pub struct ProjectHmacKeyListCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_project_id: String,
_user_project: Option<String>,
_show_deleted_keys: Option<bool>,
_service_account_email: Option<String>,
_page_token: Option<String>,
_max_results: Option<u32>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectHmacKeyListCall<'a, C> {}
impl<'a, C> ProjectHmacKeyListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, HmacKeysMetadata)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.projects.hmacKeys.list",
http_method: hyper::Method::GET,
});
for &field in [
"alt",
"projectId",
"userProject",
"showDeletedKeys",
"serviceAccountEmail",
"pageToken",
"maxResults",
]
.iter()
{
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(8 + self._additional_params.len());
params.push("projectId", self._project_id);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
if let Some(value) = self._show_deleted_keys.as_ref() {
params.push("showDeletedKeys", value.to_string());
}
if let Some(value) = self._service_account_email.as_ref() {
params.push("serviceAccountEmail", value);
}
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._max_results.as_ref() {
params.push("maxResults", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "projects/{projectId}/hmacKeys";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{projectId}", "projectId")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["projectId"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Name of the project in which to look for HMAC keys.
///
/// Sets the *project id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project_id(mut self, new_value: &str) -> ProjectHmacKeyListCall<'a, C> {
self._project_id = new_value.to_string();
self
}
/// The project to be billed for this request.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ProjectHmacKeyListCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// Whether or not to show keys in the DELETED state.
///
/// Sets the *show deleted keys* query property to the given value.
pub fn show_deleted_keys(mut self, new_value: bool) -> ProjectHmacKeyListCall<'a, C> {
self._show_deleted_keys = Some(new_value);
self
}
/// If present, only keys for the given service account are returned.
///
/// Sets the *service account email* query property to the given value.
pub fn service_account_email(mut self, new_value: &str) -> ProjectHmacKeyListCall<'a, C> {
self._service_account_email = Some(new_value.to_string());
self
}
/// A previously-returned page token representing part of the larger set of results to view.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ProjectHmacKeyListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Maximum number of items to return in a single page of responses. The service uses this parameter or 250 items, whichever is smaller. The max number of items per page will also be limited by the number of distinct service accounts in the response. If the number of service accounts in a single response is too high, the page will truncated and a next page token will be returned.
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: u32) -> ProjectHmacKeyListCall<'a, C> {
self._max_results = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ProjectHmacKeyListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ProjectHmacKeyListCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectHmacKeyListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectHmacKeyListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectHmacKeyListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Updates the state of an HMAC key. See the [HMAC Key resource descriptor](https://cloud.google.com/storage/docs/json_api/v1/projects/hmacKeys/update#request-body) for valid states.
///
/// A builder for the *hmacKeys.update* method supported by a *project* resource.
/// It is not used directly, but through a [`ProjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// use storage1::api::HmacKeyMetadata;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = HmacKeyMetadata::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.projects().hmac_keys_update(req, "projectId", "accessId")
/// .user_project("sea")
/// .doit().await;
/// # }
/// ```
pub struct ProjectHmacKeyUpdateCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_request: HmacKeyMetadata,
_project_id: String,
_access_id: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectHmacKeyUpdateCall<'a, C> {}
impl<'a, C> ProjectHmacKeyUpdateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, HmacKeyMetadata)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.projects.hmacKeys.update",
http_method: hyper::Method::PUT,
});
for &field in ["alt", "projectId", "accessId", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("projectId", self._project_id);
params.push("accessId", self._access_id);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "projects/{projectId}/hmacKeys/{accessId}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageFullControl.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in
[("{projectId}", "projectId"), ("{accessId}", "accessId")].iter()
{
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["accessId", "projectId"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PUT)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: HmacKeyMetadata) -> ProjectHmacKeyUpdateCall<'a, C> {
self._request = new_value;
self
}
/// Project ID owning the service account of the updated key.
///
/// Sets the *project id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project_id(mut self, new_value: &str) -> ProjectHmacKeyUpdateCall<'a, C> {
self._project_id = new_value.to_string();
self
}
/// Name of the HMAC key being updated.
///
/// Sets the *access id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn access_id(mut self, new_value: &str) -> ProjectHmacKeyUpdateCall<'a, C> {
self._access_id = new_value.to_string();
self
}
/// The project to be billed for this request.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ProjectHmacKeyUpdateCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ProjectHmacKeyUpdateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ProjectHmacKeyUpdateCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageFullControl`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectHmacKeyUpdateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectHmacKeyUpdateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectHmacKeyUpdateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Get the email address of this project's Google Cloud Storage service account.
///
/// A builder for the *serviceAccount.get* method supported by a *project* resource.
/// It is not used directly, but through a [`ProjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_storage1 as storage1;
/// # async fn dox() {
/// # use storage1::{Storage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_only()
/// # .enable_http2()
/// # .build();
///
/// # let executor = hyper_util::rt::TokioExecutor::new();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # yup_oauth2::client::CustomHyperClientBuilder::from(
/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
/// # ),
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http2()
/// # .build()
/// # );
/// # let mut hub = Storage::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.projects().service_account_get("projectId")
/// .user_project("amet.")
/// .doit().await;
/// # }
/// ```
pub struct ProjectServiceAccountGetCall<'a, C>
where
C: 'a,
{
hub: &'a Storage<C>,
_project_id: String,
_user_project: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectServiceAccountGetCall<'a, C> {}
impl<'a, C> ProjectServiceAccountGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ServiceAccount)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "storage.projects.serviceAccount.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "projectId", "userProject"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("projectId", self._project_id);
if let Some(value) = self._user_project.as_ref() {
params.push("userProject", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "projects/{projectId}/serviceAccount";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::DevstorageReadOnly.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{projectId}", "projectId")].iter() {
url = params.uri_replacement(url, param_name, find_this, false);
}
{
let to_remove = ["projectId"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Project ID
///
/// Sets the *project id* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project_id(mut self, new_value: &str) -> ProjectServiceAccountGetCall<'a, C> {
self._project_id = new_value.to_string();
self
}
/// The project to be billed for this request.
///
/// Sets the *user project* query property to the given value.
pub fn user_project(mut self, new_value: &str) -> ProjectServiceAccountGetCall<'a, C> {
self._user_project = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and to implement a certain level of resilience.
/// ````
///
/// Sets the *delegate* property to the given value.
pub fn delegate(
mut self,
new_value: &'a mut dyn common::Delegate,
) -> ProjectServiceAccountGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// * *uploadType* (query-string) - Upload protocol for media (e.g. "media", "multipart", "resumable").
/// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
pub fn param<T>(mut self, name: T, value: T) -> ProjectServiceAccountGetCall<'a, C>
where
T: AsRef<str>,
{
self._additional_params
.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
/// [`Scope::DevstorageReadOnly`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectServiceAccountGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectServiceAccountGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectServiceAccountGetCall<'a, C> {
self._scopes.clear();
self
}
}