google_cloudshell1/api.rs
1#![allow(clippy::ptr_arg)]
2
3use std::collections::{BTreeSet, HashMap};
4
5use tokio::time::sleep;
6
7// ##############
8// UTILITIES ###
9// ############
10
11/// Identifies the an OAuth2 authorization scope.
12/// A scope is needed when requesting an
13/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
14#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
15pub enum Scope {
16 /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
17 CloudPlatform,
18}
19
20impl AsRef<str> for Scope {
21 fn as_ref(&self) -> &str {
22 match *self {
23 Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
24 }
25 }
26}
27
28#[allow(clippy::derivable_impls)]
29impl Default for Scope {
30 fn default() -> Scope {
31 Scope::CloudPlatform
32 }
33}
34
35// ########
36// HUB ###
37// ######
38
39/// Central instance to access all CloudShell related resource activities
40///
41/// # Examples
42///
43/// Instantiate a new hub
44///
45/// ```test_harness,no_run
46/// extern crate hyper;
47/// extern crate hyper_rustls;
48/// extern crate google_cloudshell1 as cloudshell1;
49/// use cloudshell1::{Result, Error};
50/// # async fn dox() {
51/// use cloudshell1::{CloudShell, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
52///
53/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
54/// // `client_secret`, among other things.
55/// let secret: yup_oauth2::ApplicationSecret = Default::default();
56/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
57/// // unless you replace `None` with the desired Flow.
58/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
59/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
60/// // retrieve them from storage.
61/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
62/// .with_native_roots()
63/// .unwrap()
64/// .https_only()
65/// .enable_http2()
66/// .build();
67///
68/// let executor = hyper_util::rt::TokioExecutor::new();
69/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
70/// secret,
71/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
72/// yup_oauth2::client::CustomHyperClientBuilder::from(
73/// hyper_util::client::legacy::Client::builder(executor).build(connector),
74/// ),
75/// ).build().await.unwrap();
76///
77/// let client = hyper_util::client::legacy::Client::builder(
78/// hyper_util::rt::TokioExecutor::new()
79/// )
80/// .build(
81/// hyper_rustls::HttpsConnectorBuilder::new()
82/// .with_native_roots()
83/// .unwrap()
84/// .https_or_http()
85/// .enable_http2()
86/// .build()
87/// );
88/// let mut hub = CloudShell::new(client, auth);
89/// // You can configure optional parameters by calling the respective setters at will, and
90/// // execute the final call using `doit()`.
91/// // Values shown here are possibly random and not representative !
92/// let result = hub.operations().list("name")
93/// .return_partial_success(true)
94/// .page_token("gubergren")
95/// .page_size(-75)
96/// .filter("dolor")
97/// .doit().await;
98///
99/// match result {
100/// Err(e) => match e {
101/// // The Error enum provides details about what exactly happened.
102/// // You can also just use its `Debug`, `Display` or `Error` traits
103/// Error::HttpError(_)
104/// |Error::Io(_)
105/// |Error::MissingAPIKey
106/// |Error::MissingToken(_)
107/// |Error::Cancelled
108/// |Error::UploadSizeLimitExceeded(_, _)
109/// |Error::Failure(_)
110/// |Error::BadRequest(_)
111/// |Error::FieldClash(_)
112/// |Error::JsonDecodeError(_, _) => println!("{}", e),
113/// },
114/// Ok(res) => println!("Success: {:?}", res),
115/// }
116/// # }
117/// ```
118#[derive(Clone)]
119pub struct CloudShell<C> {
120 pub client: common::Client<C>,
121 pub auth: Box<dyn common::GetToken>,
122 _user_agent: String,
123 _base_url: String,
124 _root_url: String,
125}
126
127impl<C> common::Hub for CloudShell<C> {}
128
129impl<'a, C> CloudShell<C> {
130 pub fn new<A: 'static + common::GetToken>(client: common::Client<C>, auth: A) -> CloudShell<C> {
131 CloudShell {
132 client,
133 auth: Box::new(auth),
134 _user_agent: "google-api-rust-client/7.0.0".to_string(),
135 _base_url: "https://cloudshell.googleapis.com/".to_string(),
136 _root_url: "https://cloudshell.googleapis.com/".to_string(),
137 }
138 }
139
140 pub fn operations(&'a self) -> OperationMethods<'a, C> {
141 OperationMethods { hub: self }
142 }
143 pub fn users(&'a self) -> UserMethods<'a, C> {
144 UserMethods { hub: self }
145 }
146
147 /// Set the user-agent header field to use in all requests to the server.
148 /// It defaults to `google-api-rust-client/7.0.0`.
149 ///
150 /// Returns the previously set user-agent.
151 pub fn user_agent(&mut self, agent_name: String) -> String {
152 std::mem::replace(&mut self._user_agent, agent_name)
153 }
154
155 /// Set the base url to use in all requests to the server.
156 /// It defaults to `https://cloudshell.googleapis.com/`.
157 ///
158 /// Returns the previously set base url.
159 pub fn base_url(&mut self, new_base_url: String) -> String {
160 std::mem::replace(&mut self._base_url, new_base_url)
161 }
162
163 /// Set the root url to use in all requests to the server.
164 /// It defaults to `https://cloudshell.googleapis.com/`.
165 ///
166 /// Returns the previously set root url.
167 pub fn root_url(&mut self, new_root_url: String) -> String {
168 std::mem::replace(&mut self._root_url, new_root_url)
169 }
170}
171
172// ############
173// SCHEMAS ###
174// ##########
175/// Request message for AddPublicKey.
176///
177/// # Activities
178///
179/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
180/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
181///
182/// * [environments add public key users](UserEnvironmentAddPublicKeyCall) (request)
183#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
184#[serde_with::serde_as]
185#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
186pub struct AddPublicKeyRequest {
187 /// Key that should be added to the environment. Supported formats are `ssh-dss` (see RFC4253), `ssh-rsa` (see RFC4253), `ecdsa-sha2-nistp256` (see RFC5656), `ecdsa-sha2-nistp384` (see RFC5656) and `ecdsa-sha2-nistp521` (see RFC5656). It should be structured as <format> <content>, where <content> part is encoded with Base64.
188 pub key: Option<String>,
189}
190
191impl common::RequestValue for AddPublicKeyRequest {}
192
193/// Request message for AuthorizeEnvironment.
194///
195/// # Activities
196///
197/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
198/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
199///
200/// * [environments authorize users](UserEnvironmentAuthorizeCall) (request)
201#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
202#[serde_with::serde_as]
203#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
204pub struct AuthorizeEnvironmentRequest {
205 /// The OAuth access token that should be sent to the environment.
206 #[serde(rename = "accessToken")]
207 pub access_token: Option<String>,
208 /// The time when the credentials expire. If not set, defaults to one hour from when the server received the request.
209 #[serde(rename = "expireTime")]
210 pub expire_time: Option<chrono::DateTime<chrono::offset::Utc>>,
211 /// The OAuth ID token that should be sent to the environment.
212 #[serde(rename = "idToken")]
213 pub id_token: Option<String>,
214}
215
216impl common::RequestValue for AuthorizeEnvironmentRequest {}
217
218/// The request message for Operations.CancelOperation.
219///
220/// # Activities
221///
222/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
223/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
224///
225/// * [cancel operations](OperationCancelCall) (request)
226#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
227#[serde_with::serde_as]
228#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
229pub struct CancelOperationRequest {
230 _never_set: Option<bool>,
231}
232
233impl common::RequestValue for CancelOperationRequest {}
234
235/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
236///
237/// # Activities
238///
239/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
240/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
241///
242/// * [cancel operations](OperationCancelCall) (response)
243/// * [delete operations](OperationDeleteCall) (response)
244#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
245#[serde_with::serde_as]
246#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
247pub struct Empty {
248 _never_set: Option<bool>,
249}
250
251impl common::ResponseResult for Empty {}
252
253/// A Cloud Shell environment, which is defined as the combination of a Docker image specifying what is installed on the environment and a home directory containing the user’s data that will remain across sessions. Each user has at least an environment with the ID “default”.
254///
255/// # Activities
256///
257/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
258/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
259///
260/// * [environments get users](UserEnvironmentGetCall) (response)
261#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
262#[serde_with::serde_as]
263#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
264pub struct Environment {
265 /// Required. Immutable. Full path to the Docker image used to run this environment, e.g. "gcr.io/dev-con/cloud-devshell:latest".
266 #[serde(rename = "dockerImage")]
267 pub docker_image: Option<String>,
268 /// Output only. The environment's identifier, unique among the user's environments.
269 pub id: Option<String>,
270 /// Immutable. Full name of this resource, in the format `users/{owner_email}/environments/{environment_id}`. `{owner_email}` is the email address of the user to whom this environment belongs, and `{environment_id}` is the identifier of this environment. For example, `users/someone@example.com/environments/default`.
271 pub name: Option<String>,
272 /// Output only. Public keys associated with the environment. Clients can connect to this environment via SSH only if they possess a private key corresponding to at least one of these public keys. Keys can be added to or removed from the environment using the AddPublicKey and RemovePublicKey methods.
273 #[serde(rename = "publicKeys")]
274 pub public_keys: Option<Vec<String>>,
275 /// Output only. Host to which clients can connect to initiate SSH sessions with the environment.
276 #[serde(rename = "sshHost")]
277 pub ssh_host: Option<String>,
278 /// Output only. Port to which clients can connect to initiate SSH sessions with the environment.
279 #[serde(rename = "sshPort")]
280 pub ssh_port: Option<i32>,
281 /// Output only. Username that clients should use when initiating SSH sessions with the environment.
282 #[serde(rename = "sshUsername")]
283 pub ssh_username: Option<String>,
284 /// Output only. Current execution state of this environment.
285 pub state: Option<String>,
286 /// Output only. Host to which clients can connect to initiate HTTPS or WSS connections with the environment.
287 #[serde(rename = "webHost")]
288 pub web_host: Option<String>,
289}
290
291impl common::ResponseResult for Environment {}
292
293/// Response message for GenerateAccessToken.
294///
295/// # Activities
296///
297/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
298/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
299///
300/// * [environments generate access token users](UserEnvironmentGenerateAccessTokenCall) (response)
301#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
302#[serde_with::serde_as]
303#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
304pub struct GenerateAccessTokenResponse {
305 /// The access token.
306 #[serde(rename = "accessToken")]
307 pub access_token: Option<String>,
308}
309
310impl common::ResponseResult for GenerateAccessTokenResponse {}
311
312/// The response message for Operations.ListOperations.
313///
314/// # Activities
315///
316/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
317/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
318///
319/// * [list operations](OperationListCall) (response)
320#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
321#[serde_with::serde_as]
322#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
323pub struct ListOperationsResponse {
324 /// The standard List next-page token.
325 #[serde(rename = "nextPageToken")]
326 pub next_page_token: Option<String>,
327 /// A list of operations that matches the specified filter in the request.
328 pub operations: Option<Vec<Operation>>,
329 /// Unordered list. Unreachable resources. Populated when the request sets `ListOperationsRequest.return_partial_success` and reads across collections. For example, when attempting to list all resources across all supported locations.
330 pub unreachable: Option<Vec<String>>,
331}
332
333impl common::ResponseResult for ListOperationsResponse {}
334
335/// This resource represents a long-running operation that is the result of a network API call.
336///
337/// # Activities
338///
339/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
340/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
341///
342/// * [cancel operations](OperationCancelCall) (none)
343/// * [delete operations](OperationDeleteCall) (none)
344/// * [get operations](OperationGetCall) (response)
345/// * [list operations](OperationListCall) (none)
346/// * [environments add public key users](UserEnvironmentAddPublicKeyCall) (response)
347/// * [environments authorize users](UserEnvironmentAuthorizeCall) (response)
348/// * [environments remove public key users](UserEnvironmentRemovePublicKeyCall) (response)
349/// * [environments start users](UserEnvironmentStartCall) (response)
350#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
351#[serde_with::serde_as]
352#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
353pub struct Operation {
354 /// 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.
355 pub done: Option<bool>,
356 /// The error result of the operation in case of failure or cancellation.
357 pub error: Option<Status>,
358 /// 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.
359 pub metadata: Option<HashMap<String, serde_json::Value>>,
360 /// 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/{unique_id}`.
361 pub name: Option<String>,
362 /// The normal, successful response of the operation. 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`.
363 pub response: Option<HashMap<String, serde_json::Value>>,
364}
365
366impl common::Resource for Operation {}
367impl common::ResponseResult for Operation {}
368
369/// Request message for RemovePublicKey.
370///
371/// # Activities
372///
373/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
374/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
375///
376/// * [environments remove public key users](UserEnvironmentRemovePublicKeyCall) (request)
377#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
378#[serde_with::serde_as]
379#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
380pub struct RemovePublicKeyRequest {
381 /// Key that should be removed from the environment.
382 pub key: Option<String>,
383}
384
385impl common::RequestValue for RemovePublicKeyRequest {}
386
387/// Request message for StartEnvironment.
388///
389/// # Activities
390///
391/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
392/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
393///
394/// * [environments start users](UserEnvironmentStartCall) (request)
395#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
396#[serde_with::serde_as]
397#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
398pub struct StartEnvironmentRequest {
399 /// The initial access token passed to the environment. If this is present and valid, the environment will be pre-authenticated with gcloud so that the user can run gcloud commands in Cloud Shell without having to log in. This code can be updated later by calling AuthorizeEnvironment.
400 #[serde(rename = "accessToken")]
401 pub access_token: Option<String>,
402 /// Public keys that should be added to the environment before it is started.
403 #[serde(rename = "publicKeys")]
404 pub public_keys: Option<Vec<String>>,
405}
406
407impl common::RequestValue for StartEnvironmentRequest {}
408
409/// 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).
410///
411/// This type is not used in any activity, and only used as *part* of another schema.
412///
413#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
414#[serde_with::serde_as]
415#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
416pub struct Status {
417 /// The status code, which should be an enum value of google.rpc.Code.
418 pub code: Option<i32>,
419 /// A list of messages that carry the error details. There is a common set of message types for APIs to use.
420 pub details: Option<Vec<HashMap<String, serde_json::Value>>>,
421 /// A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.
422 pub message: Option<String>,
423}
424
425impl common::Part for Status {}
426
427// ###################
428// MethodBuilders ###
429// #################
430
431/// A builder providing access to all methods supported on *operation* resources.
432/// It is not used directly, but through the [`CloudShell`] hub.
433///
434/// # Example
435///
436/// Instantiate a resource builder
437///
438/// ```test_harness,no_run
439/// extern crate hyper;
440/// extern crate hyper_rustls;
441/// extern crate google_cloudshell1 as cloudshell1;
442///
443/// # async fn dox() {
444/// use cloudshell1::{CloudShell, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
445///
446/// let secret: yup_oauth2::ApplicationSecret = Default::default();
447/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
448/// .with_native_roots()
449/// .unwrap()
450/// .https_only()
451/// .enable_http2()
452/// .build();
453///
454/// let executor = hyper_util::rt::TokioExecutor::new();
455/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
456/// secret,
457/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
458/// yup_oauth2::client::CustomHyperClientBuilder::from(
459/// hyper_util::client::legacy::Client::builder(executor).build(connector),
460/// ),
461/// ).build().await.unwrap();
462///
463/// let client = hyper_util::client::legacy::Client::builder(
464/// hyper_util::rt::TokioExecutor::new()
465/// )
466/// .build(
467/// hyper_rustls::HttpsConnectorBuilder::new()
468/// .with_native_roots()
469/// .unwrap()
470/// .https_or_http()
471/// .enable_http2()
472/// .build()
473/// );
474/// let mut hub = CloudShell::new(client, auth);
475/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
476/// // like `cancel(...)`, `delete(...)`, `get(...)` and `list(...)`
477/// // to build up your call.
478/// let rb = hub.operations();
479/// # }
480/// ```
481pub struct OperationMethods<'a, C>
482where
483 C: 'a,
484{
485 hub: &'a CloudShell<C>,
486}
487
488impl<'a, C> common::MethodsBuilder for OperationMethods<'a, C> {}
489
490impl<'a, C> OperationMethods<'a, C> {
491 /// Create a builder to help you perform the following task:
492 ///
493 /// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of `1`, corresponding to `Code.CANCELLED`.
494 ///
495 /// # Arguments
496 ///
497 /// * `request` - No description provided.
498 /// * `name` - The name of the operation resource to be cancelled.
499 pub fn cancel(
500 &self,
501 request: CancelOperationRequest,
502 name: &str,
503 ) -> OperationCancelCall<'a, C> {
504 OperationCancelCall {
505 hub: self.hub,
506 _request: request,
507 _name: name.to_string(),
508 _delegate: Default::default(),
509 _additional_params: Default::default(),
510 _scopes: Default::default(),
511 }
512 }
513
514 /// Create a builder to help you perform the following task:
515 ///
516 /// Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`.
517 ///
518 /// # Arguments
519 ///
520 /// * `name` - The name of the operation resource to be deleted.
521 pub fn delete(&self, name: &str) -> OperationDeleteCall<'a, C> {
522 OperationDeleteCall {
523 hub: self.hub,
524 _name: name.to_string(),
525 _delegate: Default::default(),
526 _additional_params: Default::default(),
527 _scopes: Default::default(),
528 }
529 }
530
531 /// Create a builder to help you perform the following task:
532 ///
533 /// Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
534 ///
535 /// # Arguments
536 ///
537 /// * `name` - The name of the operation resource.
538 pub fn get(&self, name: &str) -> OperationGetCall<'a, C> {
539 OperationGetCall {
540 hub: self.hub,
541 _name: name.to_string(),
542 _delegate: Default::default(),
543 _additional_params: Default::default(),
544 _scopes: Default::default(),
545 }
546 }
547
548 /// Create a builder to help you perform the following task:
549 ///
550 /// Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`.
551 ///
552 /// # Arguments
553 ///
554 /// * `name` - The name of the operation's parent resource.
555 pub fn list(&self, name: &str) -> OperationListCall<'a, C> {
556 OperationListCall {
557 hub: self.hub,
558 _name: name.to_string(),
559 _return_partial_success: Default::default(),
560 _page_token: Default::default(),
561 _page_size: Default::default(),
562 _filter: Default::default(),
563 _delegate: Default::default(),
564 _additional_params: Default::default(),
565 _scopes: Default::default(),
566 }
567 }
568}
569
570/// A builder providing access to all methods supported on *user* resources.
571/// It is not used directly, but through the [`CloudShell`] hub.
572///
573/// # Example
574///
575/// Instantiate a resource builder
576///
577/// ```test_harness,no_run
578/// extern crate hyper;
579/// extern crate hyper_rustls;
580/// extern crate google_cloudshell1 as cloudshell1;
581///
582/// # async fn dox() {
583/// use cloudshell1::{CloudShell, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
584///
585/// let secret: yup_oauth2::ApplicationSecret = Default::default();
586/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
587/// .with_native_roots()
588/// .unwrap()
589/// .https_only()
590/// .enable_http2()
591/// .build();
592///
593/// let executor = hyper_util::rt::TokioExecutor::new();
594/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
595/// secret,
596/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
597/// yup_oauth2::client::CustomHyperClientBuilder::from(
598/// hyper_util::client::legacy::Client::builder(executor).build(connector),
599/// ),
600/// ).build().await.unwrap();
601///
602/// let client = hyper_util::client::legacy::Client::builder(
603/// hyper_util::rt::TokioExecutor::new()
604/// )
605/// .build(
606/// hyper_rustls::HttpsConnectorBuilder::new()
607/// .with_native_roots()
608/// .unwrap()
609/// .https_or_http()
610/// .enable_http2()
611/// .build()
612/// );
613/// let mut hub = CloudShell::new(client, auth);
614/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
615/// // like `environments_add_public_key(...)`, `environments_authorize(...)`, `environments_generate_access_token(...)`, `environments_get(...)`, `environments_remove_public_key(...)` and `environments_start(...)`
616/// // to build up your call.
617/// let rb = hub.users();
618/// # }
619/// ```
620pub struct UserMethods<'a, C>
621where
622 C: 'a,
623{
624 hub: &'a CloudShell<C>,
625}
626
627impl<'a, C> common::MethodsBuilder for UserMethods<'a, C> {}
628
629impl<'a, C> UserMethods<'a, C> {
630 /// Create a builder to help you perform the following task:
631 ///
632 /// Adds a public SSH key to an environment, allowing clients with the corresponding private key to connect to that environment via SSH. If a key with the same content already exists, this will error with ALREADY_EXISTS.
633 ///
634 /// # Arguments
635 ///
636 /// * `request` - No description provided.
637 /// * `environment` - Environment this key should be added to, e.g. `users/me/environments/default`.
638 pub fn environments_add_public_key(
639 &self,
640 request: AddPublicKeyRequest,
641 environment: &str,
642 ) -> UserEnvironmentAddPublicKeyCall<'a, C> {
643 UserEnvironmentAddPublicKeyCall {
644 hub: self.hub,
645 _request: request,
646 _environment: environment.to_string(),
647 _delegate: Default::default(),
648 _additional_params: Default::default(),
649 _scopes: Default::default(),
650 }
651 }
652
653 /// Create a builder to help you perform the following task:
654 ///
655 /// Sends OAuth credentials to a running environment on behalf of a user. When this completes, the environment will be authorized to run various Google Cloud command line tools without requiring the user to manually authenticate.
656 ///
657 /// # Arguments
658 ///
659 /// * `request` - No description provided.
660 /// * `name` - Name of the resource that should receive the credentials, for example `users/me/environments/default` or `users/someone@example.com/environments/default`.
661 pub fn environments_authorize(
662 &self,
663 request: AuthorizeEnvironmentRequest,
664 name: &str,
665 ) -> UserEnvironmentAuthorizeCall<'a, C> {
666 UserEnvironmentAuthorizeCall {
667 hub: self.hub,
668 _request: request,
669 _name: name.to_string(),
670 _delegate: Default::default(),
671 _additional_params: Default::default(),
672 _scopes: Default::default(),
673 }
674 }
675
676 /// Create a builder to help you perform the following task:
677 ///
678 /// Generates an access token for the user's environment.
679 ///
680 /// # Arguments
681 ///
682 /// * `environment` - Required. The environment to generate the access token for.
683 pub fn environments_generate_access_token(
684 &self,
685 environment: &str,
686 ) -> UserEnvironmentGenerateAccessTokenCall<'a, C> {
687 UserEnvironmentGenerateAccessTokenCall {
688 hub: self.hub,
689 _environment: environment.to_string(),
690 _ttl: Default::default(),
691 _expire_time: Default::default(),
692 _delegate: Default::default(),
693 _additional_params: Default::default(),
694 _scopes: Default::default(),
695 }
696 }
697
698 /// Create a builder to help you perform the following task:
699 ///
700 /// Gets an environment. Returns NOT_FOUND if the environment does not exist.
701 ///
702 /// # Arguments
703 ///
704 /// * `name` - Required. Name of the requested resource, for example `users/me/environments/default` or `users/someone@example.com/environments/default`.
705 pub fn environments_get(&self, name: &str) -> UserEnvironmentGetCall<'a, C> {
706 UserEnvironmentGetCall {
707 hub: self.hub,
708 _name: name.to_string(),
709 _delegate: Default::default(),
710 _additional_params: Default::default(),
711 _scopes: Default::default(),
712 }
713 }
714
715 /// Create a builder to help you perform the following task:
716 ///
717 /// Removes a public SSH key from an environment. Clients will no longer be able to connect to the environment using the corresponding private key. If a key with the same content is not present, this will error with NOT_FOUND.
718 ///
719 /// # Arguments
720 ///
721 /// * `request` - No description provided.
722 /// * `environment` - Environment this key should be removed from, e.g. `users/me/environments/default`.
723 pub fn environments_remove_public_key(
724 &self,
725 request: RemovePublicKeyRequest,
726 environment: &str,
727 ) -> UserEnvironmentRemovePublicKeyCall<'a, C> {
728 UserEnvironmentRemovePublicKeyCall {
729 hub: self.hub,
730 _request: request,
731 _environment: environment.to_string(),
732 _delegate: Default::default(),
733 _additional_params: Default::default(),
734 _scopes: Default::default(),
735 }
736 }
737
738 /// Create a builder to help you perform the following task:
739 ///
740 /// Starts an existing environment, allowing clients to connect to it. The returned operation will contain an instance of StartEnvironmentMetadata in its metadata field. Users can wait for the environment to start by polling this operation via GetOperation. Once the environment has finished starting and is ready to accept connections, the operation will contain a StartEnvironmentResponse in its response field.
741 ///
742 /// # Arguments
743 ///
744 /// * `request` - No description provided.
745 /// * `name` - Name of the resource that should be started, for example `users/me/environments/default` or `users/someone@example.com/environments/default`.
746 pub fn environments_start(
747 &self,
748 request: StartEnvironmentRequest,
749 name: &str,
750 ) -> UserEnvironmentStartCall<'a, C> {
751 UserEnvironmentStartCall {
752 hub: self.hub,
753 _request: request,
754 _name: name.to_string(),
755 _delegate: Default::default(),
756 _additional_params: Default::default(),
757 _scopes: Default::default(),
758 }
759 }
760}
761
762// ###################
763// CallBuilders ###
764// #################
765
766/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of `1`, corresponding to `Code.CANCELLED`.
767///
768/// A builder for the *cancel* method supported by a *operation* resource.
769/// It is not used directly, but through a [`OperationMethods`] instance.
770///
771/// # Example
772///
773/// Instantiate a resource method builder
774///
775/// ```test_harness,no_run
776/// # extern crate hyper;
777/// # extern crate hyper_rustls;
778/// # extern crate google_cloudshell1 as cloudshell1;
779/// use cloudshell1::api::CancelOperationRequest;
780/// # async fn dox() {
781/// # use cloudshell1::{CloudShell, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
782///
783/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
784/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
785/// # .with_native_roots()
786/// # .unwrap()
787/// # .https_only()
788/// # .enable_http2()
789/// # .build();
790///
791/// # let executor = hyper_util::rt::TokioExecutor::new();
792/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
793/// # secret,
794/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
795/// # yup_oauth2::client::CustomHyperClientBuilder::from(
796/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
797/// # ),
798/// # ).build().await.unwrap();
799///
800/// # let client = hyper_util::client::legacy::Client::builder(
801/// # hyper_util::rt::TokioExecutor::new()
802/// # )
803/// # .build(
804/// # hyper_rustls::HttpsConnectorBuilder::new()
805/// # .with_native_roots()
806/// # .unwrap()
807/// # .https_or_http()
808/// # .enable_http2()
809/// # .build()
810/// # );
811/// # let mut hub = CloudShell::new(client, auth);
812/// // As the method needs a request, you would usually fill it with the desired information
813/// // into the respective structure. Some of the parts shown here might not be applicable !
814/// // Values shown here are possibly random and not representative !
815/// let mut req = CancelOperationRequest::default();
816///
817/// // You can configure optional parameters by calling the respective setters at will, and
818/// // execute the final call using `doit()`.
819/// // Values shown here are possibly random and not representative !
820/// let result = hub.operations().cancel(req, "name")
821/// .doit().await;
822/// # }
823/// ```
824pub struct OperationCancelCall<'a, C>
825where
826 C: 'a,
827{
828 hub: &'a CloudShell<C>,
829 _request: CancelOperationRequest,
830 _name: String,
831 _delegate: Option<&'a mut dyn common::Delegate>,
832 _additional_params: HashMap<String, String>,
833 _scopes: BTreeSet<String>,
834}
835
836impl<'a, C> common::CallBuilder for OperationCancelCall<'a, C> {}
837
838impl<'a, C> OperationCancelCall<'a, C>
839where
840 C: common::Connector,
841{
842 /// Perform the operation you have build so far.
843 pub async fn doit(mut self) -> common::Result<(common::Response, Empty)> {
844 use std::borrow::Cow;
845 use std::io::{Read, Seek};
846
847 use common::{url::Params, ToParts};
848 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
849
850 let mut dd = common::DefaultDelegate;
851 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
852 dlg.begin(common::MethodInfo {
853 id: "cloudshell.operations.cancel",
854 http_method: hyper::Method::POST,
855 });
856
857 for &field in ["alt", "name"].iter() {
858 if self._additional_params.contains_key(field) {
859 dlg.finished(false);
860 return Err(common::Error::FieldClash(field));
861 }
862 }
863
864 let mut params = Params::with_capacity(4 + self._additional_params.len());
865 params.push("name", self._name);
866
867 params.extend(self._additional_params.iter());
868
869 params.push("alt", "json");
870 let mut url = self.hub._base_url.clone() + "v1/{+name}:cancel";
871 if self._scopes.is_empty() {
872 self._scopes
873 .insert(Scope::CloudPlatform.as_ref().to_string());
874 }
875
876 #[allow(clippy::single_element_loop)]
877 for &(find_this, param_name) in [("{+name}", "name")].iter() {
878 url = params.uri_replacement(url, param_name, find_this, true);
879 }
880 {
881 let to_remove = ["name"];
882 params.remove_params(&to_remove);
883 }
884
885 let url = params.parse_with_url(&url);
886
887 let mut json_mime_type = mime::APPLICATION_JSON;
888 let mut request_value_reader = {
889 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
890 common::remove_json_null_values(&mut value);
891 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
892 serde_json::to_writer(&mut dst, &value).unwrap();
893 dst
894 };
895 let request_size = request_value_reader
896 .seek(std::io::SeekFrom::End(0))
897 .unwrap();
898 request_value_reader
899 .seek(std::io::SeekFrom::Start(0))
900 .unwrap();
901
902 loop {
903 let token = match self
904 .hub
905 .auth
906 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
907 .await
908 {
909 Ok(token) => token,
910 Err(e) => match dlg.token(e) {
911 Ok(token) => token,
912 Err(e) => {
913 dlg.finished(false);
914 return Err(common::Error::MissingToken(e));
915 }
916 },
917 };
918 request_value_reader
919 .seek(std::io::SeekFrom::Start(0))
920 .unwrap();
921 let mut req_result = {
922 let client = &self.hub.client;
923 dlg.pre_request();
924 let mut req_builder = hyper::Request::builder()
925 .method(hyper::Method::POST)
926 .uri(url.as_str())
927 .header(USER_AGENT, self.hub._user_agent.clone());
928
929 if let Some(token) = token.as_ref() {
930 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
931 }
932
933 let request = req_builder
934 .header(CONTENT_TYPE, json_mime_type.to_string())
935 .header(CONTENT_LENGTH, request_size as u64)
936 .body(common::to_body(
937 request_value_reader.get_ref().clone().into(),
938 ));
939
940 client.request(request.unwrap()).await
941 };
942
943 match req_result {
944 Err(err) => {
945 if let common::Retry::After(d) = dlg.http_error(&err) {
946 sleep(d).await;
947 continue;
948 }
949 dlg.finished(false);
950 return Err(common::Error::HttpError(err));
951 }
952 Ok(res) => {
953 let (mut parts, body) = res.into_parts();
954 let mut body = common::Body::new(body);
955 if !parts.status.is_success() {
956 let bytes = common::to_bytes(body).await.unwrap_or_default();
957 let error = serde_json::from_str(&common::to_string(&bytes));
958 let response = common::to_response(parts, bytes.into());
959
960 if let common::Retry::After(d) =
961 dlg.http_failure(&response, error.as_ref().ok())
962 {
963 sleep(d).await;
964 continue;
965 }
966
967 dlg.finished(false);
968
969 return Err(match error {
970 Ok(value) => common::Error::BadRequest(value),
971 _ => common::Error::Failure(response),
972 });
973 }
974 let response = {
975 let bytes = common::to_bytes(body).await.unwrap_or_default();
976 let encoded = common::to_string(&bytes);
977 match serde_json::from_str(&encoded) {
978 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
979 Err(error) => {
980 dlg.response_json_decode_error(&encoded, &error);
981 return Err(common::Error::JsonDecodeError(
982 encoded.to_string(),
983 error,
984 ));
985 }
986 }
987 };
988
989 dlg.finished(true);
990 return Ok(response);
991 }
992 }
993 }
994 }
995
996 ///
997 /// Sets the *request* property to the given value.
998 ///
999 /// Even though the property as already been set when instantiating this call,
1000 /// we provide this method for API completeness.
1001 pub fn request(mut self, new_value: CancelOperationRequest) -> OperationCancelCall<'a, C> {
1002 self._request = new_value;
1003 self
1004 }
1005 /// The name of the operation resource to be cancelled.
1006 ///
1007 /// Sets the *name* path property to the given value.
1008 ///
1009 /// Even though the property as already been set when instantiating this call,
1010 /// we provide this method for API completeness.
1011 pub fn name(mut self, new_value: &str) -> OperationCancelCall<'a, C> {
1012 self._name = new_value.to_string();
1013 self
1014 }
1015 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1016 /// while executing the actual API request.
1017 ///
1018 /// ````text
1019 /// It should be used to handle progress information, and to implement a certain level of resilience.
1020 /// ````
1021 ///
1022 /// Sets the *delegate* property to the given value.
1023 pub fn delegate(
1024 mut self,
1025 new_value: &'a mut dyn common::Delegate,
1026 ) -> OperationCancelCall<'a, C> {
1027 self._delegate = Some(new_value);
1028 self
1029 }
1030
1031 /// Set any additional parameter of the query string used in the request.
1032 /// It should be used to set parameters which are not yet available through their own
1033 /// setters.
1034 ///
1035 /// Please note that this method must not be used to set any of the known parameters
1036 /// which have their own setter method. If done anyway, the request will fail.
1037 ///
1038 /// # Additional Parameters
1039 ///
1040 /// * *$.xgafv* (query-string) - V1 error format.
1041 /// * *access_token* (query-string) - OAuth access token.
1042 /// * *alt* (query-string) - Data format for response.
1043 /// * *callback* (query-string) - JSONP
1044 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1045 /// * *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.
1046 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1047 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1048 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1049 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1050 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1051 pub fn param<T>(mut self, name: T, value: T) -> OperationCancelCall<'a, C>
1052 where
1053 T: AsRef<str>,
1054 {
1055 self._additional_params
1056 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1057 self
1058 }
1059
1060 /// Identifies the authorization scope for the method you are building.
1061 ///
1062 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1063 /// [`Scope::CloudPlatform`].
1064 ///
1065 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1066 /// tokens for more than one scope.
1067 ///
1068 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1069 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1070 /// sufficient, a read-write scope will do as well.
1071 pub fn add_scope<St>(mut self, scope: St) -> OperationCancelCall<'a, C>
1072 where
1073 St: AsRef<str>,
1074 {
1075 self._scopes.insert(String::from(scope.as_ref()));
1076 self
1077 }
1078 /// Identifies the authorization scope(s) for the method you are building.
1079 ///
1080 /// See [`Self::add_scope()`] for details.
1081 pub fn add_scopes<I, St>(mut self, scopes: I) -> OperationCancelCall<'a, C>
1082 where
1083 I: IntoIterator<Item = St>,
1084 St: AsRef<str>,
1085 {
1086 self._scopes
1087 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1088 self
1089 }
1090
1091 /// Removes all scopes, and no default scope will be used either.
1092 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1093 /// for details).
1094 pub fn clear_scopes(mut self) -> OperationCancelCall<'a, C> {
1095 self._scopes.clear();
1096 self
1097 }
1098}
1099
1100/// Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`.
1101///
1102/// A builder for the *delete* method supported by a *operation* resource.
1103/// It is not used directly, but through a [`OperationMethods`] instance.
1104///
1105/// # Example
1106///
1107/// Instantiate a resource method builder
1108///
1109/// ```test_harness,no_run
1110/// # extern crate hyper;
1111/// # extern crate hyper_rustls;
1112/// # extern crate google_cloudshell1 as cloudshell1;
1113/// # async fn dox() {
1114/// # use cloudshell1::{CloudShell, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1115///
1116/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1117/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1118/// # .with_native_roots()
1119/// # .unwrap()
1120/// # .https_only()
1121/// # .enable_http2()
1122/// # .build();
1123///
1124/// # let executor = hyper_util::rt::TokioExecutor::new();
1125/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1126/// # secret,
1127/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1128/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1129/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1130/// # ),
1131/// # ).build().await.unwrap();
1132///
1133/// # let client = hyper_util::client::legacy::Client::builder(
1134/// # hyper_util::rt::TokioExecutor::new()
1135/// # )
1136/// # .build(
1137/// # hyper_rustls::HttpsConnectorBuilder::new()
1138/// # .with_native_roots()
1139/// # .unwrap()
1140/// # .https_or_http()
1141/// # .enable_http2()
1142/// # .build()
1143/// # );
1144/// # let mut hub = CloudShell::new(client, auth);
1145/// // You can configure optional parameters by calling the respective setters at will, and
1146/// // execute the final call using `doit()`.
1147/// // Values shown here are possibly random and not representative !
1148/// let result = hub.operations().delete("name")
1149/// .doit().await;
1150/// # }
1151/// ```
1152pub struct OperationDeleteCall<'a, C>
1153where
1154 C: 'a,
1155{
1156 hub: &'a CloudShell<C>,
1157 _name: String,
1158 _delegate: Option<&'a mut dyn common::Delegate>,
1159 _additional_params: HashMap<String, String>,
1160 _scopes: BTreeSet<String>,
1161}
1162
1163impl<'a, C> common::CallBuilder for OperationDeleteCall<'a, C> {}
1164
1165impl<'a, C> OperationDeleteCall<'a, C>
1166where
1167 C: common::Connector,
1168{
1169 /// Perform the operation you have build so far.
1170 pub async fn doit(mut self) -> common::Result<(common::Response, Empty)> {
1171 use std::borrow::Cow;
1172 use std::io::{Read, Seek};
1173
1174 use common::{url::Params, ToParts};
1175 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1176
1177 let mut dd = common::DefaultDelegate;
1178 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1179 dlg.begin(common::MethodInfo {
1180 id: "cloudshell.operations.delete",
1181 http_method: hyper::Method::DELETE,
1182 });
1183
1184 for &field in ["alt", "name"].iter() {
1185 if self._additional_params.contains_key(field) {
1186 dlg.finished(false);
1187 return Err(common::Error::FieldClash(field));
1188 }
1189 }
1190
1191 let mut params = Params::with_capacity(3 + self._additional_params.len());
1192 params.push("name", self._name);
1193
1194 params.extend(self._additional_params.iter());
1195
1196 params.push("alt", "json");
1197 let mut url = self.hub._base_url.clone() + "v1/{+name}";
1198 if self._scopes.is_empty() {
1199 self._scopes
1200 .insert(Scope::CloudPlatform.as_ref().to_string());
1201 }
1202
1203 #[allow(clippy::single_element_loop)]
1204 for &(find_this, param_name) in [("{+name}", "name")].iter() {
1205 url = params.uri_replacement(url, param_name, find_this, true);
1206 }
1207 {
1208 let to_remove = ["name"];
1209 params.remove_params(&to_remove);
1210 }
1211
1212 let url = params.parse_with_url(&url);
1213
1214 loop {
1215 let token = match self
1216 .hub
1217 .auth
1218 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1219 .await
1220 {
1221 Ok(token) => token,
1222 Err(e) => match dlg.token(e) {
1223 Ok(token) => token,
1224 Err(e) => {
1225 dlg.finished(false);
1226 return Err(common::Error::MissingToken(e));
1227 }
1228 },
1229 };
1230 let mut req_result = {
1231 let client = &self.hub.client;
1232 dlg.pre_request();
1233 let mut req_builder = hyper::Request::builder()
1234 .method(hyper::Method::DELETE)
1235 .uri(url.as_str())
1236 .header(USER_AGENT, self.hub._user_agent.clone());
1237
1238 if let Some(token) = token.as_ref() {
1239 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1240 }
1241
1242 let request = req_builder
1243 .header(CONTENT_LENGTH, 0_u64)
1244 .body(common::to_body::<String>(None));
1245
1246 client.request(request.unwrap()).await
1247 };
1248
1249 match req_result {
1250 Err(err) => {
1251 if let common::Retry::After(d) = dlg.http_error(&err) {
1252 sleep(d).await;
1253 continue;
1254 }
1255 dlg.finished(false);
1256 return Err(common::Error::HttpError(err));
1257 }
1258 Ok(res) => {
1259 let (mut parts, body) = res.into_parts();
1260 let mut body = common::Body::new(body);
1261 if !parts.status.is_success() {
1262 let bytes = common::to_bytes(body).await.unwrap_or_default();
1263 let error = serde_json::from_str(&common::to_string(&bytes));
1264 let response = common::to_response(parts, bytes.into());
1265
1266 if let common::Retry::After(d) =
1267 dlg.http_failure(&response, error.as_ref().ok())
1268 {
1269 sleep(d).await;
1270 continue;
1271 }
1272
1273 dlg.finished(false);
1274
1275 return Err(match error {
1276 Ok(value) => common::Error::BadRequest(value),
1277 _ => common::Error::Failure(response),
1278 });
1279 }
1280 let response = {
1281 let bytes = common::to_bytes(body).await.unwrap_or_default();
1282 let encoded = common::to_string(&bytes);
1283 match serde_json::from_str(&encoded) {
1284 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1285 Err(error) => {
1286 dlg.response_json_decode_error(&encoded, &error);
1287 return Err(common::Error::JsonDecodeError(
1288 encoded.to_string(),
1289 error,
1290 ));
1291 }
1292 }
1293 };
1294
1295 dlg.finished(true);
1296 return Ok(response);
1297 }
1298 }
1299 }
1300 }
1301
1302 /// The name of the operation resource to be deleted.
1303 ///
1304 /// Sets the *name* path property to the given value.
1305 ///
1306 /// Even though the property as already been set when instantiating this call,
1307 /// we provide this method for API completeness.
1308 pub fn name(mut self, new_value: &str) -> OperationDeleteCall<'a, C> {
1309 self._name = new_value.to_string();
1310 self
1311 }
1312 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1313 /// while executing the actual API request.
1314 ///
1315 /// ````text
1316 /// It should be used to handle progress information, and to implement a certain level of resilience.
1317 /// ````
1318 ///
1319 /// Sets the *delegate* property to the given value.
1320 pub fn delegate(
1321 mut self,
1322 new_value: &'a mut dyn common::Delegate,
1323 ) -> OperationDeleteCall<'a, C> {
1324 self._delegate = Some(new_value);
1325 self
1326 }
1327
1328 /// Set any additional parameter of the query string used in the request.
1329 /// It should be used to set parameters which are not yet available through their own
1330 /// setters.
1331 ///
1332 /// Please note that this method must not be used to set any of the known parameters
1333 /// which have their own setter method. If done anyway, the request will fail.
1334 ///
1335 /// # Additional Parameters
1336 ///
1337 /// * *$.xgafv* (query-string) - V1 error format.
1338 /// * *access_token* (query-string) - OAuth access token.
1339 /// * *alt* (query-string) - Data format for response.
1340 /// * *callback* (query-string) - JSONP
1341 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1342 /// * *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.
1343 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1344 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1345 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1346 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1347 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1348 pub fn param<T>(mut self, name: T, value: T) -> OperationDeleteCall<'a, C>
1349 where
1350 T: AsRef<str>,
1351 {
1352 self._additional_params
1353 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1354 self
1355 }
1356
1357 /// Identifies the authorization scope for the method you are building.
1358 ///
1359 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1360 /// [`Scope::CloudPlatform`].
1361 ///
1362 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1363 /// tokens for more than one scope.
1364 ///
1365 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1366 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1367 /// sufficient, a read-write scope will do as well.
1368 pub fn add_scope<St>(mut self, scope: St) -> OperationDeleteCall<'a, C>
1369 where
1370 St: AsRef<str>,
1371 {
1372 self._scopes.insert(String::from(scope.as_ref()));
1373 self
1374 }
1375 /// Identifies the authorization scope(s) for the method you are building.
1376 ///
1377 /// See [`Self::add_scope()`] for details.
1378 pub fn add_scopes<I, St>(mut self, scopes: I) -> OperationDeleteCall<'a, C>
1379 where
1380 I: IntoIterator<Item = St>,
1381 St: AsRef<str>,
1382 {
1383 self._scopes
1384 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1385 self
1386 }
1387
1388 /// Removes all scopes, and no default scope will be used either.
1389 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1390 /// for details).
1391 pub fn clear_scopes(mut self) -> OperationDeleteCall<'a, C> {
1392 self._scopes.clear();
1393 self
1394 }
1395}
1396
1397/// Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
1398///
1399/// A builder for the *get* method supported by a *operation* resource.
1400/// It is not used directly, but through a [`OperationMethods`] instance.
1401///
1402/// # Example
1403///
1404/// Instantiate a resource method builder
1405///
1406/// ```test_harness,no_run
1407/// # extern crate hyper;
1408/// # extern crate hyper_rustls;
1409/// # extern crate google_cloudshell1 as cloudshell1;
1410/// # async fn dox() {
1411/// # use cloudshell1::{CloudShell, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1412///
1413/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1414/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1415/// # .with_native_roots()
1416/// # .unwrap()
1417/// # .https_only()
1418/// # .enable_http2()
1419/// # .build();
1420///
1421/// # let executor = hyper_util::rt::TokioExecutor::new();
1422/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1423/// # secret,
1424/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1425/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1426/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1427/// # ),
1428/// # ).build().await.unwrap();
1429///
1430/// # let client = hyper_util::client::legacy::Client::builder(
1431/// # hyper_util::rt::TokioExecutor::new()
1432/// # )
1433/// # .build(
1434/// # hyper_rustls::HttpsConnectorBuilder::new()
1435/// # .with_native_roots()
1436/// # .unwrap()
1437/// # .https_or_http()
1438/// # .enable_http2()
1439/// # .build()
1440/// # );
1441/// # let mut hub = CloudShell::new(client, auth);
1442/// // You can configure optional parameters by calling the respective setters at will, and
1443/// // execute the final call using `doit()`.
1444/// // Values shown here are possibly random and not representative !
1445/// let result = hub.operations().get("name")
1446/// .doit().await;
1447/// # }
1448/// ```
1449pub struct OperationGetCall<'a, C>
1450where
1451 C: 'a,
1452{
1453 hub: &'a CloudShell<C>,
1454 _name: String,
1455 _delegate: Option<&'a mut dyn common::Delegate>,
1456 _additional_params: HashMap<String, String>,
1457 _scopes: BTreeSet<String>,
1458}
1459
1460impl<'a, C> common::CallBuilder for OperationGetCall<'a, C> {}
1461
1462impl<'a, C> OperationGetCall<'a, C>
1463where
1464 C: common::Connector,
1465{
1466 /// Perform the operation you have build so far.
1467 pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
1468 use std::borrow::Cow;
1469 use std::io::{Read, Seek};
1470
1471 use common::{url::Params, ToParts};
1472 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1473
1474 let mut dd = common::DefaultDelegate;
1475 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1476 dlg.begin(common::MethodInfo {
1477 id: "cloudshell.operations.get",
1478 http_method: hyper::Method::GET,
1479 });
1480
1481 for &field in ["alt", "name"].iter() {
1482 if self._additional_params.contains_key(field) {
1483 dlg.finished(false);
1484 return Err(common::Error::FieldClash(field));
1485 }
1486 }
1487
1488 let mut params = Params::with_capacity(3 + self._additional_params.len());
1489 params.push("name", self._name);
1490
1491 params.extend(self._additional_params.iter());
1492
1493 params.push("alt", "json");
1494 let mut url = self.hub._base_url.clone() + "v1/{+name}";
1495 if self._scopes.is_empty() {
1496 self._scopes
1497 .insert(Scope::CloudPlatform.as_ref().to_string());
1498 }
1499
1500 #[allow(clippy::single_element_loop)]
1501 for &(find_this, param_name) in [("{+name}", "name")].iter() {
1502 url = params.uri_replacement(url, param_name, find_this, true);
1503 }
1504 {
1505 let to_remove = ["name"];
1506 params.remove_params(&to_remove);
1507 }
1508
1509 let url = params.parse_with_url(&url);
1510
1511 loop {
1512 let token = match self
1513 .hub
1514 .auth
1515 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1516 .await
1517 {
1518 Ok(token) => token,
1519 Err(e) => match dlg.token(e) {
1520 Ok(token) => token,
1521 Err(e) => {
1522 dlg.finished(false);
1523 return Err(common::Error::MissingToken(e));
1524 }
1525 },
1526 };
1527 let mut req_result = {
1528 let client = &self.hub.client;
1529 dlg.pre_request();
1530 let mut req_builder = hyper::Request::builder()
1531 .method(hyper::Method::GET)
1532 .uri(url.as_str())
1533 .header(USER_AGENT, self.hub._user_agent.clone());
1534
1535 if let Some(token) = token.as_ref() {
1536 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1537 }
1538
1539 let request = req_builder
1540 .header(CONTENT_LENGTH, 0_u64)
1541 .body(common::to_body::<String>(None));
1542
1543 client.request(request.unwrap()).await
1544 };
1545
1546 match req_result {
1547 Err(err) => {
1548 if let common::Retry::After(d) = dlg.http_error(&err) {
1549 sleep(d).await;
1550 continue;
1551 }
1552 dlg.finished(false);
1553 return Err(common::Error::HttpError(err));
1554 }
1555 Ok(res) => {
1556 let (mut parts, body) = res.into_parts();
1557 let mut body = common::Body::new(body);
1558 if !parts.status.is_success() {
1559 let bytes = common::to_bytes(body).await.unwrap_or_default();
1560 let error = serde_json::from_str(&common::to_string(&bytes));
1561 let response = common::to_response(parts, bytes.into());
1562
1563 if let common::Retry::After(d) =
1564 dlg.http_failure(&response, error.as_ref().ok())
1565 {
1566 sleep(d).await;
1567 continue;
1568 }
1569
1570 dlg.finished(false);
1571
1572 return Err(match error {
1573 Ok(value) => common::Error::BadRequest(value),
1574 _ => common::Error::Failure(response),
1575 });
1576 }
1577 let response = {
1578 let bytes = common::to_bytes(body).await.unwrap_or_default();
1579 let encoded = common::to_string(&bytes);
1580 match serde_json::from_str(&encoded) {
1581 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1582 Err(error) => {
1583 dlg.response_json_decode_error(&encoded, &error);
1584 return Err(common::Error::JsonDecodeError(
1585 encoded.to_string(),
1586 error,
1587 ));
1588 }
1589 }
1590 };
1591
1592 dlg.finished(true);
1593 return Ok(response);
1594 }
1595 }
1596 }
1597 }
1598
1599 /// The name of the operation resource.
1600 ///
1601 /// Sets the *name* path property to the given value.
1602 ///
1603 /// Even though the property as already been set when instantiating this call,
1604 /// we provide this method for API completeness.
1605 pub fn name(mut self, new_value: &str) -> OperationGetCall<'a, C> {
1606 self._name = new_value.to_string();
1607 self
1608 }
1609 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1610 /// while executing the actual API request.
1611 ///
1612 /// ````text
1613 /// It should be used to handle progress information, and to implement a certain level of resilience.
1614 /// ````
1615 ///
1616 /// Sets the *delegate* property to the given value.
1617 pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> OperationGetCall<'a, C> {
1618 self._delegate = Some(new_value);
1619 self
1620 }
1621
1622 /// Set any additional parameter of the query string used in the request.
1623 /// It should be used to set parameters which are not yet available through their own
1624 /// setters.
1625 ///
1626 /// Please note that this method must not be used to set any of the known parameters
1627 /// which have their own setter method. If done anyway, the request will fail.
1628 ///
1629 /// # Additional Parameters
1630 ///
1631 /// * *$.xgafv* (query-string) - V1 error format.
1632 /// * *access_token* (query-string) - OAuth access token.
1633 /// * *alt* (query-string) - Data format for response.
1634 /// * *callback* (query-string) - JSONP
1635 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1636 /// * *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.
1637 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1638 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1639 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1640 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1641 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1642 pub fn param<T>(mut self, name: T, value: T) -> OperationGetCall<'a, C>
1643 where
1644 T: AsRef<str>,
1645 {
1646 self._additional_params
1647 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1648 self
1649 }
1650
1651 /// Identifies the authorization scope for the method you are building.
1652 ///
1653 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1654 /// [`Scope::CloudPlatform`].
1655 ///
1656 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1657 /// tokens for more than one scope.
1658 ///
1659 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1660 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1661 /// sufficient, a read-write scope will do as well.
1662 pub fn add_scope<St>(mut self, scope: St) -> OperationGetCall<'a, C>
1663 where
1664 St: AsRef<str>,
1665 {
1666 self._scopes.insert(String::from(scope.as_ref()));
1667 self
1668 }
1669 /// Identifies the authorization scope(s) for the method you are building.
1670 ///
1671 /// See [`Self::add_scope()`] for details.
1672 pub fn add_scopes<I, St>(mut self, scopes: I) -> OperationGetCall<'a, C>
1673 where
1674 I: IntoIterator<Item = St>,
1675 St: AsRef<str>,
1676 {
1677 self._scopes
1678 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1679 self
1680 }
1681
1682 /// Removes all scopes, and no default scope will be used either.
1683 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1684 /// for details).
1685 pub fn clear_scopes(mut self) -> OperationGetCall<'a, C> {
1686 self._scopes.clear();
1687 self
1688 }
1689}
1690
1691/// Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`.
1692///
1693/// A builder for the *list* method supported by a *operation* resource.
1694/// It is not used directly, but through a [`OperationMethods`] instance.
1695///
1696/// # Example
1697///
1698/// Instantiate a resource method builder
1699///
1700/// ```test_harness,no_run
1701/// # extern crate hyper;
1702/// # extern crate hyper_rustls;
1703/// # extern crate google_cloudshell1 as cloudshell1;
1704/// # async fn dox() {
1705/// # use cloudshell1::{CloudShell, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1706///
1707/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1708/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1709/// # .with_native_roots()
1710/// # .unwrap()
1711/// # .https_only()
1712/// # .enable_http2()
1713/// # .build();
1714///
1715/// # let executor = hyper_util::rt::TokioExecutor::new();
1716/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1717/// # secret,
1718/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1719/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1720/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1721/// # ),
1722/// # ).build().await.unwrap();
1723///
1724/// # let client = hyper_util::client::legacy::Client::builder(
1725/// # hyper_util::rt::TokioExecutor::new()
1726/// # )
1727/// # .build(
1728/// # hyper_rustls::HttpsConnectorBuilder::new()
1729/// # .with_native_roots()
1730/// # .unwrap()
1731/// # .https_or_http()
1732/// # .enable_http2()
1733/// # .build()
1734/// # );
1735/// # let mut hub = CloudShell::new(client, auth);
1736/// // You can configure optional parameters by calling the respective setters at will, and
1737/// // execute the final call using `doit()`.
1738/// // Values shown here are possibly random and not representative !
1739/// let result = hub.operations().list("name")
1740/// .return_partial_success(true)
1741/// .page_token("sed")
1742/// .page_size(-37)
1743/// .filter("gubergren")
1744/// .doit().await;
1745/// # }
1746/// ```
1747pub struct OperationListCall<'a, C>
1748where
1749 C: 'a,
1750{
1751 hub: &'a CloudShell<C>,
1752 _name: String,
1753 _return_partial_success: Option<bool>,
1754 _page_token: Option<String>,
1755 _page_size: Option<i32>,
1756 _filter: Option<String>,
1757 _delegate: Option<&'a mut dyn common::Delegate>,
1758 _additional_params: HashMap<String, String>,
1759 _scopes: BTreeSet<String>,
1760}
1761
1762impl<'a, C> common::CallBuilder for OperationListCall<'a, C> {}
1763
1764impl<'a, C> OperationListCall<'a, C>
1765where
1766 C: common::Connector,
1767{
1768 /// Perform the operation you have build so far.
1769 pub async fn doit(mut self) -> common::Result<(common::Response, ListOperationsResponse)> {
1770 use std::borrow::Cow;
1771 use std::io::{Read, Seek};
1772
1773 use common::{url::Params, ToParts};
1774 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1775
1776 let mut dd = common::DefaultDelegate;
1777 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1778 dlg.begin(common::MethodInfo {
1779 id: "cloudshell.operations.list",
1780 http_method: hyper::Method::GET,
1781 });
1782
1783 for &field in [
1784 "alt",
1785 "name",
1786 "returnPartialSuccess",
1787 "pageToken",
1788 "pageSize",
1789 "filter",
1790 ]
1791 .iter()
1792 {
1793 if self._additional_params.contains_key(field) {
1794 dlg.finished(false);
1795 return Err(common::Error::FieldClash(field));
1796 }
1797 }
1798
1799 let mut params = Params::with_capacity(7 + self._additional_params.len());
1800 params.push("name", self._name);
1801 if let Some(value) = self._return_partial_success.as_ref() {
1802 params.push("returnPartialSuccess", value.to_string());
1803 }
1804 if let Some(value) = self._page_token.as_ref() {
1805 params.push("pageToken", value);
1806 }
1807 if let Some(value) = self._page_size.as_ref() {
1808 params.push("pageSize", value.to_string());
1809 }
1810 if let Some(value) = self._filter.as_ref() {
1811 params.push("filter", value);
1812 }
1813
1814 params.extend(self._additional_params.iter());
1815
1816 params.push("alt", "json");
1817 let mut url = self.hub._base_url.clone() + "v1/{+name}";
1818 if self._scopes.is_empty() {
1819 self._scopes
1820 .insert(Scope::CloudPlatform.as_ref().to_string());
1821 }
1822
1823 #[allow(clippy::single_element_loop)]
1824 for &(find_this, param_name) in [("{+name}", "name")].iter() {
1825 url = params.uri_replacement(url, param_name, find_this, true);
1826 }
1827 {
1828 let to_remove = ["name"];
1829 params.remove_params(&to_remove);
1830 }
1831
1832 let url = params.parse_with_url(&url);
1833
1834 loop {
1835 let token = match self
1836 .hub
1837 .auth
1838 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1839 .await
1840 {
1841 Ok(token) => token,
1842 Err(e) => match dlg.token(e) {
1843 Ok(token) => token,
1844 Err(e) => {
1845 dlg.finished(false);
1846 return Err(common::Error::MissingToken(e));
1847 }
1848 },
1849 };
1850 let mut req_result = {
1851 let client = &self.hub.client;
1852 dlg.pre_request();
1853 let mut req_builder = hyper::Request::builder()
1854 .method(hyper::Method::GET)
1855 .uri(url.as_str())
1856 .header(USER_AGENT, self.hub._user_agent.clone());
1857
1858 if let Some(token) = token.as_ref() {
1859 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1860 }
1861
1862 let request = req_builder
1863 .header(CONTENT_LENGTH, 0_u64)
1864 .body(common::to_body::<String>(None));
1865
1866 client.request(request.unwrap()).await
1867 };
1868
1869 match req_result {
1870 Err(err) => {
1871 if let common::Retry::After(d) = dlg.http_error(&err) {
1872 sleep(d).await;
1873 continue;
1874 }
1875 dlg.finished(false);
1876 return Err(common::Error::HttpError(err));
1877 }
1878 Ok(res) => {
1879 let (mut parts, body) = res.into_parts();
1880 let mut body = common::Body::new(body);
1881 if !parts.status.is_success() {
1882 let bytes = common::to_bytes(body).await.unwrap_or_default();
1883 let error = serde_json::from_str(&common::to_string(&bytes));
1884 let response = common::to_response(parts, bytes.into());
1885
1886 if let common::Retry::After(d) =
1887 dlg.http_failure(&response, error.as_ref().ok())
1888 {
1889 sleep(d).await;
1890 continue;
1891 }
1892
1893 dlg.finished(false);
1894
1895 return Err(match error {
1896 Ok(value) => common::Error::BadRequest(value),
1897 _ => common::Error::Failure(response),
1898 });
1899 }
1900 let response = {
1901 let bytes = common::to_bytes(body).await.unwrap_or_default();
1902 let encoded = common::to_string(&bytes);
1903 match serde_json::from_str(&encoded) {
1904 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1905 Err(error) => {
1906 dlg.response_json_decode_error(&encoded, &error);
1907 return Err(common::Error::JsonDecodeError(
1908 encoded.to_string(),
1909 error,
1910 ));
1911 }
1912 }
1913 };
1914
1915 dlg.finished(true);
1916 return Ok(response);
1917 }
1918 }
1919 }
1920 }
1921
1922 /// The name of the operation's parent resource.
1923 ///
1924 /// Sets the *name* path property to the given value.
1925 ///
1926 /// Even though the property as already been set when instantiating this call,
1927 /// we provide this method for API completeness.
1928 pub fn name(mut self, new_value: &str) -> OperationListCall<'a, C> {
1929 self._name = new_value.to_string();
1930 self
1931 }
1932 /// When set to `true`, operations that are reachable are returned as normal, and those that are unreachable are returned in the ListOperationsResponse.unreachable field. This can only be `true` when reading across collections. For example, when `parent` is set to `"projects/example/locations/-"`. This field is not supported by default and will result in an `UNIMPLEMENTED` error if set unless explicitly documented otherwise in service or product specific documentation.
1933 ///
1934 /// Sets the *return partial success* query property to the given value.
1935 pub fn return_partial_success(mut self, new_value: bool) -> OperationListCall<'a, C> {
1936 self._return_partial_success = Some(new_value);
1937 self
1938 }
1939 /// The standard list page token.
1940 ///
1941 /// Sets the *page token* query property to the given value.
1942 pub fn page_token(mut self, new_value: &str) -> OperationListCall<'a, C> {
1943 self._page_token = Some(new_value.to_string());
1944 self
1945 }
1946 /// The standard list page size.
1947 ///
1948 /// Sets the *page size* query property to the given value.
1949 pub fn page_size(mut self, new_value: i32) -> OperationListCall<'a, C> {
1950 self._page_size = Some(new_value);
1951 self
1952 }
1953 /// The standard list filter.
1954 ///
1955 /// Sets the *filter* query property to the given value.
1956 pub fn filter(mut self, new_value: &str) -> OperationListCall<'a, C> {
1957 self._filter = Some(new_value.to_string());
1958 self
1959 }
1960 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1961 /// while executing the actual API request.
1962 ///
1963 /// ````text
1964 /// It should be used to handle progress information, and to implement a certain level of resilience.
1965 /// ````
1966 ///
1967 /// Sets the *delegate* property to the given value.
1968 pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> OperationListCall<'a, C> {
1969 self._delegate = Some(new_value);
1970 self
1971 }
1972
1973 /// Set any additional parameter of the query string used in the request.
1974 /// It should be used to set parameters which are not yet available through their own
1975 /// setters.
1976 ///
1977 /// Please note that this method must not be used to set any of the known parameters
1978 /// which have their own setter method. If done anyway, the request will fail.
1979 ///
1980 /// # Additional Parameters
1981 ///
1982 /// * *$.xgafv* (query-string) - V1 error format.
1983 /// * *access_token* (query-string) - OAuth access token.
1984 /// * *alt* (query-string) - Data format for response.
1985 /// * *callback* (query-string) - JSONP
1986 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1987 /// * *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.
1988 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1989 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1990 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1991 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1992 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1993 pub fn param<T>(mut self, name: T, value: T) -> OperationListCall<'a, C>
1994 where
1995 T: AsRef<str>,
1996 {
1997 self._additional_params
1998 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1999 self
2000 }
2001
2002 /// Identifies the authorization scope for the method you are building.
2003 ///
2004 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2005 /// [`Scope::CloudPlatform`].
2006 ///
2007 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2008 /// tokens for more than one scope.
2009 ///
2010 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2011 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2012 /// sufficient, a read-write scope will do as well.
2013 pub fn add_scope<St>(mut self, scope: St) -> OperationListCall<'a, C>
2014 where
2015 St: AsRef<str>,
2016 {
2017 self._scopes.insert(String::from(scope.as_ref()));
2018 self
2019 }
2020 /// Identifies the authorization scope(s) for the method you are building.
2021 ///
2022 /// See [`Self::add_scope()`] for details.
2023 pub fn add_scopes<I, St>(mut self, scopes: I) -> OperationListCall<'a, C>
2024 where
2025 I: IntoIterator<Item = St>,
2026 St: AsRef<str>,
2027 {
2028 self._scopes
2029 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2030 self
2031 }
2032
2033 /// Removes all scopes, and no default scope will be used either.
2034 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2035 /// for details).
2036 pub fn clear_scopes(mut self) -> OperationListCall<'a, C> {
2037 self._scopes.clear();
2038 self
2039 }
2040}
2041
2042/// Adds a public SSH key to an environment, allowing clients with the corresponding private key to connect to that environment via SSH. If a key with the same content already exists, this will error with ALREADY_EXISTS.
2043///
2044/// A builder for the *environments.addPublicKey* method supported by a *user* resource.
2045/// It is not used directly, but through a [`UserMethods`] instance.
2046///
2047/// # Example
2048///
2049/// Instantiate a resource method builder
2050///
2051/// ```test_harness,no_run
2052/// # extern crate hyper;
2053/// # extern crate hyper_rustls;
2054/// # extern crate google_cloudshell1 as cloudshell1;
2055/// use cloudshell1::api::AddPublicKeyRequest;
2056/// # async fn dox() {
2057/// # use cloudshell1::{CloudShell, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2058///
2059/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2060/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2061/// # .with_native_roots()
2062/// # .unwrap()
2063/// # .https_only()
2064/// # .enable_http2()
2065/// # .build();
2066///
2067/// # let executor = hyper_util::rt::TokioExecutor::new();
2068/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2069/// # secret,
2070/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2071/// # yup_oauth2::client::CustomHyperClientBuilder::from(
2072/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
2073/// # ),
2074/// # ).build().await.unwrap();
2075///
2076/// # let client = hyper_util::client::legacy::Client::builder(
2077/// # hyper_util::rt::TokioExecutor::new()
2078/// # )
2079/// # .build(
2080/// # hyper_rustls::HttpsConnectorBuilder::new()
2081/// # .with_native_roots()
2082/// # .unwrap()
2083/// # .https_or_http()
2084/// # .enable_http2()
2085/// # .build()
2086/// # );
2087/// # let mut hub = CloudShell::new(client, auth);
2088/// // As the method needs a request, you would usually fill it with the desired information
2089/// // into the respective structure. Some of the parts shown here might not be applicable !
2090/// // Values shown here are possibly random and not representative !
2091/// let mut req = AddPublicKeyRequest::default();
2092///
2093/// // You can configure optional parameters by calling the respective setters at will, and
2094/// // execute the final call using `doit()`.
2095/// // Values shown here are possibly random and not representative !
2096/// let result = hub.users().environments_add_public_key(req, "environment")
2097/// .doit().await;
2098/// # }
2099/// ```
2100pub struct UserEnvironmentAddPublicKeyCall<'a, C>
2101where
2102 C: 'a,
2103{
2104 hub: &'a CloudShell<C>,
2105 _request: AddPublicKeyRequest,
2106 _environment: String,
2107 _delegate: Option<&'a mut dyn common::Delegate>,
2108 _additional_params: HashMap<String, String>,
2109 _scopes: BTreeSet<String>,
2110}
2111
2112impl<'a, C> common::CallBuilder for UserEnvironmentAddPublicKeyCall<'a, C> {}
2113
2114impl<'a, C> UserEnvironmentAddPublicKeyCall<'a, C>
2115where
2116 C: common::Connector,
2117{
2118 /// Perform the operation you have build so far.
2119 pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
2120 use std::borrow::Cow;
2121 use std::io::{Read, Seek};
2122
2123 use common::{url::Params, ToParts};
2124 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2125
2126 let mut dd = common::DefaultDelegate;
2127 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2128 dlg.begin(common::MethodInfo {
2129 id: "cloudshell.users.environments.addPublicKey",
2130 http_method: hyper::Method::POST,
2131 });
2132
2133 for &field in ["alt", "environment"].iter() {
2134 if self._additional_params.contains_key(field) {
2135 dlg.finished(false);
2136 return Err(common::Error::FieldClash(field));
2137 }
2138 }
2139
2140 let mut params = Params::with_capacity(4 + self._additional_params.len());
2141 params.push("environment", self._environment);
2142
2143 params.extend(self._additional_params.iter());
2144
2145 params.push("alt", "json");
2146 let mut url = self.hub._base_url.clone() + "v1/{+environment}:addPublicKey";
2147 if self._scopes.is_empty() {
2148 self._scopes
2149 .insert(Scope::CloudPlatform.as_ref().to_string());
2150 }
2151
2152 #[allow(clippy::single_element_loop)]
2153 for &(find_this, param_name) in [("{+environment}", "environment")].iter() {
2154 url = params.uri_replacement(url, param_name, find_this, true);
2155 }
2156 {
2157 let to_remove = ["environment"];
2158 params.remove_params(&to_remove);
2159 }
2160
2161 let url = params.parse_with_url(&url);
2162
2163 let mut json_mime_type = mime::APPLICATION_JSON;
2164 let mut request_value_reader = {
2165 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2166 common::remove_json_null_values(&mut value);
2167 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2168 serde_json::to_writer(&mut dst, &value).unwrap();
2169 dst
2170 };
2171 let request_size = request_value_reader
2172 .seek(std::io::SeekFrom::End(0))
2173 .unwrap();
2174 request_value_reader
2175 .seek(std::io::SeekFrom::Start(0))
2176 .unwrap();
2177
2178 loop {
2179 let token = match self
2180 .hub
2181 .auth
2182 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2183 .await
2184 {
2185 Ok(token) => token,
2186 Err(e) => match dlg.token(e) {
2187 Ok(token) => token,
2188 Err(e) => {
2189 dlg.finished(false);
2190 return Err(common::Error::MissingToken(e));
2191 }
2192 },
2193 };
2194 request_value_reader
2195 .seek(std::io::SeekFrom::Start(0))
2196 .unwrap();
2197 let mut req_result = {
2198 let client = &self.hub.client;
2199 dlg.pre_request();
2200 let mut req_builder = hyper::Request::builder()
2201 .method(hyper::Method::POST)
2202 .uri(url.as_str())
2203 .header(USER_AGENT, self.hub._user_agent.clone());
2204
2205 if let Some(token) = token.as_ref() {
2206 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2207 }
2208
2209 let request = req_builder
2210 .header(CONTENT_TYPE, json_mime_type.to_string())
2211 .header(CONTENT_LENGTH, request_size as u64)
2212 .body(common::to_body(
2213 request_value_reader.get_ref().clone().into(),
2214 ));
2215
2216 client.request(request.unwrap()).await
2217 };
2218
2219 match req_result {
2220 Err(err) => {
2221 if let common::Retry::After(d) = dlg.http_error(&err) {
2222 sleep(d).await;
2223 continue;
2224 }
2225 dlg.finished(false);
2226 return Err(common::Error::HttpError(err));
2227 }
2228 Ok(res) => {
2229 let (mut parts, body) = res.into_parts();
2230 let mut body = common::Body::new(body);
2231 if !parts.status.is_success() {
2232 let bytes = common::to_bytes(body).await.unwrap_or_default();
2233 let error = serde_json::from_str(&common::to_string(&bytes));
2234 let response = common::to_response(parts, bytes.into());
2235
2236 if let common::Retry::After(d) =
2237 dlg.http_failure(&response, error.as_ref().ok())
2238 {
2239 sleep(d).await;
2240 continue;
2241 }
2242
2243 dlg.finished(false);
2244
2245 return Err(match error {
2246 Ok(value) => common::Error::BadRequest(value),
2247 _ => common::Error::Failure(response),
2248 });
2249 }
2250 let response = {
2251 let bytes = common::to_bytes(body).await.unwrap_or_default();
2252 let encoded = common::to_string(&bytes);
2253 match serde_json::from_str(&encoded) {
2254 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2255 Err(error) => {
2256 dlg.response_json_decode_error(&encoded, &error);
2257 return Err(common::Error::JsonDecodeError(
2258 encoded.to_string(),
2259 error,
2260 ));
2261 }
2262 }
2263 };
2264
2265 dlg.finished(true);
2266 return Ok(response);
2267 }
2268 }
2269 }
2270 }
2271
2272 ///
2273 /// Sets the *request* property to the given value.
2274 ///
2275 /// Even though the property as already been set when instantiating this call,
2276 /// we provide this method for API completeness.
2277 pub fn request(
2278 mut self,
2279 new_value: AddPublicKeyRequest,
2280 ) -> UserEnvironmentAddPublicKeyCall<'a, C> {
2281 self._request = new_value;
2282 self
2283 }
2284 /// Environment this key should be added to, e.g. `users/me/environments/default`.
2285 ///
2286 /// Sets the *environment* path property to the given value.
2287 ///
2288 /// Even though the property as already been set when instantiating this call,
2289 /// we provide this method for API completeness.
2290 pub fn environment(mut self, new_value: &str) -> UserEnvironmentAddPublicKeyCall<'a, C> {
2291 self._environment = new_value.to_string();
2292 self
2293 }
2294 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2295 /// while executing the actual API request.
2296 ///
2297 /// ````text
2298 /// It should be used to handle progress information, and to implement a certain level of resilience.
2299 /// ````
2300 ///
2301 /// Sets the *delegate* property to the given value.
2302 pub fn delegate(
2303 mut self,
2304 new_value: &'a mut dyn common::Delegate,
2305 ) -> UserEnvironmentAddPublicKeyCall<'a, C> {
2306 self._delegate = Some(new_value);
2307 self
2308 }
2309
2310 /// Set any additional parameter of the query string used in the request.
2311 /// It should be used to set parameters which are not yet available through their own
2312 /// setters.
2313 ///
2314 /// Please note that this method must not be used to set any of the known parameters
2315 /// which have their own setter method. If done anyway, the request will fail.
2316 ///
2317 /// # Additional Parameters
2318 ///
2319 /// * *$.xgafv* (query-string) - V1 error format.
2320 /// * *access_token* (query-string) - OAuth access token.
2321 /// * *alt* (query-string) - Data format for response.
2322 /// * *callback* (query-string) - JSONP
2323 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2324 /// * *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.
2325 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2326 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2327 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
2328 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2329 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2330 pub fn param<T>(mut self, name: T, value: T) -> UserEnvironmentAddPublicKeyCall<'a, C>
2331 where
2332 T: AsRef<str>,
2333 {
2334 self._additional_params
2335 .insert(name.as_ref().to_string(), value.as_ref().to_string());
2336 self
2337 }
2338
2339 /// Identifies the authorization scope for the method you are building.
2340 ///
2341 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2342 /// [`Scope::CloudPlatform`].
2343 ///
2344 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2345 /// tokens for more than one scope.
2346 ///
2347 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2348 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2349 /// sufficient, a read-write scope will do as well.
2350 pub fn add_scope<St>(mut self, scope: St) -> UserEnvironmentAddPublicKeyCall<'a, C>
2351 where
2352 St: AsRef<str>,
2353 {
2354 self._scopes.insert(String::from(scope.as_ref()));
2355 self
2356 }
2357 /// Identifies the authorization scope(s) for the method you are building.
2358 ///
2359 /// See [`Self::add_scope()`] for details.
2360 pub fn add_scopes<I, St>(mut self, scopes: I) -> UserEnvironmentAddPublicKeyCall<'a, C>
2361 where
2362 I: IntoIterator<Item = St>,
2363 St: AsRef<str>,
2364 {
2365 self._scopes
2366 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2367 self
2368 }
2369
2370 /// Removes all scopes, and no default scope will be used either.
2371 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2372 /// for details).
2373 pub fn clear_scopes(mut self) -> UserEnvironmentAddPublicKeyCall<'a, C> {
2374 self._scopes.clear();
2375 self
2376 }
2377}
2378
2379/// Sends OAuth credentials to a running environment on behalf of a user. When this completes, the environment will be authorized to run various Google Cloud command line tools without requiring the user to manually authenticate.
2380///
2381/// A builder for the *environments.authorize* method supported by a *user* resource.
2382/// It is not used directly, but through a [`UserMethods`] instance.
2383///
2384/// # Example
2385///
2386/// Instantiate a resource method builder
2387///
2388/// ```test_harness,no_run
2389/// # extern crate hyper;
2390/// # extern crate hyper_rustls;
2391/// # extern crate google_cloudshell1 as cloudshell1;
2392/// use cloudshell1::api::AuthorizeEnvironmentRequest;
2393/// # async fn dox() {
2394/// # use cloudshell1::{CloudShell, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2395///
2396/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2397/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2398/// # .with_native_roots()
2399/// # .unwrap()
2400/// # .https_only()
2401/// # .enable_http2()
2402/// # .build();
2403///
2404/// # let executor = hyper_util::rt::TokioExecutor::new();
2405/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2406/// # secret,
2407/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2408/// # yup_oauth2::client::CustomHyperClientBuilder::from(
2409/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
2410/// # ),
2411/// # ).build().await.unwrap();
2412///
2413/// # let client = hyper_util::client::legacy::Client::builder(
2414/// # hyper_util::rt::TokioExecutor::new()
2415/// # )
2416/// # .build(
2417/// # hyper_rustls::HttpsConnectorBuilder::new()
2418/// # .with_native_roots()
2419/// # .unwrap()
2420/// # .https_or_http()
2421/// # .enable_http2()
2422/// # .build()
2423/// # );
2424/// # let mut hub = CloudShell::new(client, auth);
2425/// // As the method needs a request, you would usually fill it with the desired information
2426/// // into the respective structure. Some of the parts shown here might not be applicable !
2427/// // Values shown here are possibly random and not representative !
2428/// let mut req = AuthorizeEnvironmentRequest::default();
2429///
2430/// // You can configure optional parameters by calling the respective setters at will, and
2431/// // execute the final call using `doit()`.
2432/// // Values shown here are possibly random and not representative !
2433/// let result = hub.users().environments_authorize(req, "name")
2434/// .doit().await;
2435/// # }
2436/// ```
2437pub struct UserEnvironmentAuthorizeCall<'a, C>
2438where
2439 C: 'a,
2440{
2441 hub: &'a CloudShell<C>,
2442 _request: AuthorizeEnvironmentRequest,
2443 _name: String,
2444 _delegate: Option<&'a mut dyn common::Delegate>,
2445 _additional_params: HashMap<String, String>,
2446 _scopes: BTreeSet<String>,
2447}
2448
2449impl<'a, C> common::CallBuilder for UserEnvironmentAuthorizeCall<'a, C> {}
2450
2451impl<'a, C> UserEnvironmentAuthorizeCall<'a, C>
2452where
2453 C: common::Connector,
2454{
2455 /// Perform the operation you have build so far.
2456 pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
2457 use std::borrow::Cow;
2458 use std::io::{Read, Seek};
2459
2460 use common::{url::Params, ToParts};
2461 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2462
2463 let mut dd = common::DefaultDelegate;
2464 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2465 dlg.begin(common::MethodInfo {
2466 id: "cloudshell.users.environments.authorize",
2467 http_method: hyper::Method::POST,
2468 });
2469
2470 for &field in ["alt", "name"].iter() {
2471 if self._additional_params.contains_key(field) {
2472 dlg.finished(false);
2473 return Err(common::Error::FieldClash(field));
2474 }
2475 }
2476
2477 let mut params = Params::with_capacity(4 + self._additional_params.len());
2478 params.push("name", self._name);
2479
2480 params.extend(self._additional_params.iter());
2481
2482 params.push("alt", "json");
2483 let mut url = self.hub._base_url.clone() + "v1/{+name}:authorize";
2484 if self._scopes.is_empty() {
2485 self._scopes
2486 .insert(Scope::CloudPlatform.as_ref().to_string());
2487 }
2488
2489 #[allow(clippy::single_element_loop)]
2490 for &(find_this, param_name) in [("{+name}", "name")].iter() {
2491 url = params.uri_replacement(url, param_name, find_this, true);
2492 }
2493 {
2494 let to_remove = ["name"];
2495 params.remove_params(&to_remove);
2496 }
2497
2498 let url = params.parse_with_url(&url);
2499
2500 let mut json_mime_type = mime::APPLICATION_JSON;
2501 let mut request_value_reader = {
2502 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2503 common::remove_json_null_values(&mut value);
2504 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2505 serde_json::to_writer(&mut dst, &value).unwrap();
2506 dst
2507 };
2508 let request_size = request_value_reader
2509 .seek(std::io::SeekFrom::End(0))
2510 .unwrap();
2511 request_value_reader
2512 .seek(std::io::SeekFrom::Start(0))
2513 .unwrap();
2514
2515 loop {
2516 let token = match self
2517 .hub
2518 .auth
2519 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2520 .await
2521 {
2522 Ok(token) => token,
2523 Err(e) => match dlg.token(e) {
2524 Ok(token) => token,
2525 Err(e) => {
2526 dlg.finished(false);
2527 return Err(common::Error::MissingToken(e));
2528 }
2529 },
2530 };
2531 request_value_reader
2532 .seek(std::io::SeekFrom::Start(0))
2533 .unwrap();
2534 let mut req_result = {
2535 let client = &self.hub.client;
2536 dlg.pre_request();
2537 let mut req_builder = hyper::Request::builder()
2538 .method(hyper::Method::POST)
2539 .uri(url.as_str())
2540 .header(USER_AGENT, self.hub._user_agent.clone());
2541
2542 if let Some(token) = token.as_ref() {
2543 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2544 }
2545
2546 let request = req_builder
2547 .header(CONTENT_TYPE, json_mime_type.to_string())
2548 .header(CONTENT_LENGTH, request_size as u64)
2549 .body(common::to_body(
2550 request_value_reader.get_ref().clone().into(),
2551 ));
2552
2553 client.request(request.unwrap()).await
2554 };
2555
2556 match req_result {
2557 Err(err) => {
2558 if let common::Retry::After(d) = dlg.http_error(&err) {
2559 sleep(d).await;
2560 continue;
2561 }
2562 dlg.finished(false);
2563 return Err(common::Error::HttpError(err));
2564 }
2565 Ok(res) => {
2566 let (mut parts, body) = res.into_parts();
2567 let mut body = common::Body::new(body);
2568 if !parts.status.is_success() {
2569 let bytes = common::to_bytes(body).await.unwrap_or_default();
2570 let error = serde_json::from_str(&common::to_string(&bytes));
2571 let response = common::to_response(parts, bytes.into());
2572
2573 if let common::Retry::After(d) =
2574 dlg.http_failure(&response, error.as_ref().ok())
2575 {
2576 sleep(d).await;
2577 continue;
2578 }
2579
2580 dlg.finished(false);
2581
2582 return Err(match error {
2583 Ok(value) => common::Error::BadRequest(value),
2584 _ => common::Error::Failure(response),
2585 });
2586 }
2587 let response = {
2588 let bytes = common::to_bytes(body).await.unwrap_or_default();
2589 let encoded = common::to_string(&bytes);
2590 match serde_json::from_str(&encoded) {
2591 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2592 Err(error) => {
2593 dlg.response_json_decode_error(&encoded, &error);
2594 return Err(common::Error::JsonDecodeError(
2595 encoded.to_string(),
2596 error,
2597 ));
2598 }
2599 }
2600 };
2601
2602 dlg.finished(true);
2603 return Ok(response);
2604 }
2605 }
2606 }
2607 }
2608
2609 ///
2610 /// Sets the *request* property to the given value.
2611 ///
2612 /// Even though the property as already been set when instantiating this call,
2613 /// we provide this method for API completeness.
2614 pub fn request(
2615 mut self,
2616 new_value: AuthorizeEnvironmentRequest,
2617 ) -> UserEnvironmentAuthorizeCall<'a, C> {
2618 self._request = new_value;
2619 self
2620 }
2621 /// Name of the resource that should receive the credentials, for example `users/me/environments/default` or `users/someone@example.com/environments/default`.
2622 ///
2623 /// Sets the *name* path property to the given value.
2624 ///
2625 /// Even though the property as already been set when instantiating this call,
2626 /// we provide this method for API completeness.
2627 pub fn name(mut self, new_value: &str) -> UserEnvironmentAuthorizeCall<'a, C> {
2628 self._name = new_value.to_string();
2629 self
2630 }
2631 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2632 /// while executing the actual API request.
2633 ///
2634 /// ````text
2635 /// It should be used to handle progress information, and to implement a certain level of resilience.
2636 /// ````
2637 ///
2638 /// Sets the *delegate* property to the given value.
2639 pub fn delegate(
2640 mut self,
2641 new_value: &'a mut dyn common::Delegate,
2642 ) -> UserEnvironmentAuthorizeCall<'a, C> {
2643 self._delegate = Some(new_value);
2644 self
2645 }
2646
2647 /// Set any additional parameter of the query string used in the request.
2648 /// It should be used to set parameters which are not yet available through their own
2649 /// setters.
2650 ///
2651 /// Please note that this method must not be used to set any of the known parameters
2652 /// which have their own setter method. If done anyway, the request will fail.
2653 ///
2654 /// # Additional Parameters
2655 ///
2656 /// * *$.xgafv* (query-string) - V1 error format.
2657 /// * *access_token* (query-string) - OAuth access token.
2658 /// * *alt* (query-string) - Data format for response.
2659 /// * *callback* (query-string) - JSONP
2660 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2661 /// * *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.
2662 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2663 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2664 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
2665 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2666 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2667 pub fn param<T>(mut self, name: T, value: T) -> UserEnvironmentAuthorizeCall<'a, C>
2668 where
2669 T: AsRef<str>,
2670 {
2671 self._additional_params
2672 .insert(name.as_ref().to_string(), value.as_ref().to_string());
2673 self
2674 }
2675
2676 /// Identifies the authorization scope for the method you are building.
2677 ///
2678 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2679 /// [`Scope::CloudPlatform`].
2680 ///
2681 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2682 /// tokens for more than one scope.
2683 ///
2684 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2685 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2686 /// sufficient, a read-write scope will do as well.
2687 pub fn add_scope<St>(mut self, scope: St) -> UserEnvironmentAuthorizeCall<'a, C>
2688 where
2689 St: AsRef<str>,
2690 {
2691 self._scopes.insert(String::from(scope.as_ref()));
2692 self
2693 }
2694 /// Identifies the authorization scope(s) for the method you are building.
2695 ///
2696 /// See [`Self::add_scope()`] for details.
2697 pub fn add_scopes<I, St>(mut self, scopes: I) -> UserEnvironmentAuthorizeCall<'a, C>
2698 where
2699 I: IntoIterator<Item = St>,
2700 St: AsRef<str>,
2701 {
2702 self._scopes
2703 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2704 self
2705 }
2706
2707 /// Removes all scopes, and no default scope will be used either.
2708 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2709 /// for details).
2710 pub fn clear_scopes(mut self) -> UserEnvironmentAuthorizeCall<'a, C> {
2711 self._scopes.clear();
2712 self
2713 }
2714}
2715
2716/// Generates an access token for the user's environment.
2717///
2718/// A builder for the *environments.generateAccessToken* method supported by a *user* resource.
2719/// It is not used directly, but through a [`UserMethods`] instance.
2720///
2721/// # Example
2722///
2723/// Instantiate a resource method builder
2724///
2725/// ```test_harness,no_run
2726/// # extern crate hyper;
2727/// # extern crate hyper_rustls;
2728/// # extern crate google_cloudshell1 as cloudshell1;
2729/// # async fn dox() {
2730/// # use cloudshell1::{CloudShell, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2731///
2732/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2733/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2734/// # .with_native_roots()
2735/// # .unwrap()
2736/// # .https_only()
2737/// # .enable_http2()
2738/// # .build();
2739///
2740/// # let executor = hyper_util::rt::TokioExecutor::new();
2741/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2742/// # secret,
2743/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2744/// # yup_oauth2::client::CustomHyperClientBuilder::from(
2745/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
2746/// # ),
2747/// # ).build().await.unwrap();
2748///
2749/// # let client = hyper_util::client::legacy::Client::builder(
2750/// # hyper_util::rt::TokioExecutor::new()
2751/// # )
2752/// # .build(
2753/// # hyper_rustls::HttpsConnectorBuilder::new()
2754/// # .with_native_roots()
2755/// # .unwrap()
2756/// # .https_or_http()
2757/// # .enable_http2()
2758/// # .build()
2759/// # );
2760/// # let mut hub = CloudShell::new(client, auth);
2761/// // You can configure optional parameters by calling the respective setters at will, and
2762/// // execute the final call using `doit()`.
2763/// // Values shown here are possibly random and not representative !
2764/// let result = hub.users().environments_generate_access_token("environment")
2765/// .ttl(chrono::Duration::seconds(6767418))
2766/// .expire_time(chrono::Utc::now())
2767/// .doit().await;
2768/// # }
2769/// ```
2770pub struct UserEnvironmentGenerateAccessTokenCall<'a, C>
2771where
2772 C: 'a,
2773{
2774 hub: &'a CloudShell<C>,
2775 _environment: String,
2776 _ttl: Option<chrono::Duration>,
2777 _expire_time: Option<chrono::DateTime<chrono::offset::Utc>>,
2778 _delegate: Option<&'a mut dyn common::Delegate>,
2779 _additional_params: HashMap<String, String>,
2780 _scopes: BTreeSet<String>,
2781}
2782
2783impl<'a, C> common::CallBuilder for UserEnvironmentGenerateAccessTokenCall<'a, C> {}
2784
2785impl<'a, C> UserEnvironmentGenerateAccessTokenCall<'a, C>
2786where
2787 C: common::Connector,
2788{
2789 /// Perform the operation you have build so far.
2790 pub async fn doit(mut self) -> common::Result<(common::Response, GenerateAccessTokenResponse)> {
2791 use std::borrow::Cow;
2792 use std::io::{Read, Seek};
2793
2794 use common::{url::Params, ToParts};
2795 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2796
2797 let mut dd = common::DefaultDelegate;
2798 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2799 dlg.begin(common::MethodInfo {
2800 id: "cloudshell.users.environments.generateAccessToken",
2801 http_method: hyper::Method::GET,
2802 });
2803
2804 for &field in ["alt", "environment", "ttl", "expireTime"].iter() {
2805 if self._additional_params.contains_key(field) {
2806 dlg.finished(false);
2807 return Err(common::Error::FieldClash(field));
2808 }
2809 }
2810
2811 let mut params = Params::with_capacity(5 + self._additional_params.len());
2812 params.push("environment", self._environment);
2813 if let Some(value) = self._ttl.as_ref() {
2814 params.push("ttl", common::serde::duration::to_string(&value));
2815 }
2816 if let Some(value) = self._expire_time.as_ref() {
2817 params.push("expireTime", common::serde::datetime_to_string(&value));
2818 }
2819
2820 params.extend(self._additional_params.iter());
2821
2822 params.push("alt", "json");
2823 let mut url = self.hub._base_url.clone() + "v1/{+environment}:generateAccessToken";
2824 if self._scopes.is_empty() {
2825 self._scopes
2826 .insert(Scope::CloudPlatform.as_ref().to_string());
2827 }
2828
2829 #[allow(clippy::single_element_loop)]
2830 for &(find_this, param_name) in [("{+environment}", "environment")].iter() {
2831 url = params.uri_replacement(url, param_name, find_this, true);
2832 }
2833 {
2834 let to_remove = ["environment"];
2835 params.remove_params(&to_remove);
2836 }
2837
2838 let url = params.parse_with_url(&url);
2839
2840 loop {
2841 let token = match self
2842 .hub
2843 .auth
2844 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2845 .await
2846 {
2847 Ok(token) => token,
2848 Err(e) => match dlg.token(e) {
2849 Ok(token) => token,
2850 Err(e) => {
2851 dlg.finished(false);
2852 return Err(common::Error::MissingToken(e));
2853 }
2854 },
2855 };
2856 let mut req_result = {
2857 let client = &self.hub.client;
2858 dlg.pre_request();
2859 let mut req_builder = hyper::Request::builder()
2860 .method(hyper::Method::GET)
2861 .uri(url.as_str())
2862 .header(USER_AGENT, self.hub._user_agent.clone());
2863
2864 if let Some(token) = token.as_ref() {
2865 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2866 }
2867
2868 let request = req_builder
2869 .header(CONTENT_LENGTH, 0_u64)
2870 .body(common::to_body::<String>(None));
2871
2872 client.request(request.unwrap()).await
2873 };
2874
2875 match req_result {
2876 Err(err) => {
2877 if let common::Retry::After(d) = dlg.http_error(&err) {
2878 sleep(d).await;
2879 continue;
2880 }
2881 dlg.finished(false);
2882 return Err(common::Error::HttpError(err));
2883 }
2884 Ok(res) => {
2885 let (mut parts, body) = res.into_parts();
2886 let mut body = common::Body::new(body);
2887 if !parts.status.is_success() {
2888 let bytes = common::to_bytes(body).await.unwrap_or_default();
2889 let error = serde_json::from_str(&common::to_string(&bytes));
2890 let response = common::to_response(parts, bytes.into());
2891
2892 if let common::Retry::After(d) =
2893 dlg.http_failure(&response, error.as_ref().ok())
2894 {
2895 sleep(d).await;
2896 continue;
2897 }
2898
2899 dlg.finished(false);
2900
2901 return Err(match error {
2902 Ok(value) => common::Error::BadRequest(value),
2903 _ => common::Error::Failure(response),
2904 });
2905 }
2906 let response = {
2907 let bytes = common::to_bytes(body).await.unwrap_or_default();
2908 let encoded = common::to_string(&bytes);
2909 match serde_json::from_str(&encoded) {
2910 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2911 Err(error) => {
2912 dlg.response_json_decode_error(&encoded, &error);
2913 return Err(common::Error::JsonDecodeError(
2914 encoded.to_string(),
2915 error,
2916 ));
2917 }
2918 }
2919 };
2920
2921 dlg.finished(true);
2922 return Ok(response);
2923 }
2924 }
2925 }
2926 }
2927
2928 /// Required. The environment to generate the access token for.
2929 ///
2930 /// Sets the *environment* path property to the given value.
2931 ///
2932 /// Even though the property as already been set when instantiating this call,
2933 /// we provide this method for API completeness.
2934 pub fn environment(mut self, new_value: &str) -> UserEnvironmentGenerateAccessTokenCall<'a, C> {
2935 self._environment = new_value.to_string();
2936 self
2937 }
2938 /// Desired lifetime duration of the access token. This value must be at most 24 hours. If a value is not specified, the token's lifetime will be set to a default value of 1 hour.
2939 ///
2940 /// Sets the *ttl* query property to the given value.
2941 pub fn ttl(
2942 mut self,
2943 new_value: chrono::Duration,
2944 ) -> UserEnvironmentGenerateAccessTokenCall<'a, C> {
2945 self._ttl = Some(new_value);
2946 self
2947 }
2948 /// Desired expiration time of the access token. This value must be at most 24 hours in the future. If a value is not specified, the token's expiration time will be set to a default value of 1 hour in the future.
2949 ///
2950 /// Sets the *expire time* query property to the given value.
2951 pub fn expire_time(
2952 mut self,
2953 new_value: chrono::DateTime<chrono::offset::Utc>,
2954 ) -> UserEnvironmentGenerateAccessTokenCall<'a, C> {
2955 self._expire_time = Some(new_value);
2956 self
2957 }
2958 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2959 /// while executing the actual API request.
2960 ///
2961 /// ````text
2962 /// It should be used to handle progress information, and to implement a certain level of resilience.
2963 /// ````
2964 ///
2965 /// Sets the *delegate* property to the given value.
2966 pub fn delegate(
2967 mut self,
2968 new_value: &'a mut dyn common::Delegate,
2969 ) -> UserEnvironmentGenerateAccessTokenCall<'a, C> {
2970 self._delegate = Some(new_value);
2971 self
2972 }
2973
2974 /// Set any additional parameter of the query string used in the request.
2975 /// It should be used to set parameters which are not yet available through their own
2976 /// setters.
2977 ///
2978 /// Please note that this method must not be used to set any of the known parameters
2979 /// which have their own setter method. If done anyway, the request will fail.
2980 ///
2981 /// # Additional Parameters
2982 ///
2983 /// * *$.xgafv* (query-string) - V1 error format.
2984 /// * *access_token* (query-string) - OAuth access token.
2985 /// * *alt* (query-string) - Data format for response.
2986 /// * *callback* (query-string) - JSONP
2987 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2988 /// * *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.
2989 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2990 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2991 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
2992 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2993 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2994 pub fn param<T>(mut self, name: T, value: T) -> UserEnvironmentGenerateAccessTokenCall<'a, C>
2995 where
2996 T: AsRef<str>,
2997 {
2998 self._additional_params
2999 .insert(name.as_ref().to_string(), value.as_ref().to_string());
3000 self
3001 }
3002
3003 /// Identifies the authorization scope for the method you are building.
3004 ///
3005 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
3006 /// [`Scope::CloudPlatform`].
3007 ///
3008 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
3009 /// tokens for more than one scope.
3010 ///
3011 /// Usually there is more than one suitable scope to authorize an operation, some of which may
3012 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
3013 /// sufficient, a read-write scope will do as well.
3014 pub fn add_scope<St>(mut self, scope: St) -> UserEnvironmentGenerateAccessTokenCall<'a, C>
3015 where
3016 St: AsRef<str>,
3017 {
3018 self._scopes.insert(String::from(scope.as_ref()));
3019 self
3020 }
3021 /// Identifies the authorization scope(s) for the method you are building.
3022 ///
3023 /// See [`Self::add_scope()`] for details.
3024 pub fn add_scopes<I, St>(mut self, scopes: I) -> UserEnvironmentGenerateAccessTokenCall<'a, C>
3025 where
3026 I: IntoIterator<Item = St>,
3027 St: AsRef<str>,
3028 {
3029 self._scopes
3030 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
3031 self
3032 }
3033
3034 /// Removes all scopes, and no default scope will be used either.
3035 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
3036 /// for details).
3037 pub fn clear_scopes(mut self) -> UserEnvironmentGenerateAccessTokenCall<'a, C> {
3038 self._scopes.clear();
3039 self
3040 }
3041}
3042
3043/// Gets an environment. Returns NOT_FOUND if the environment does not exist.
3044///
3045/// A builder for the *environments.get* method supported by a *user* resource.
3046/// It is not used directly, but through a [`UserMethods`] instance.
3047///
3048/// # Example
3049///
3050/// Instantiate a resource method builder
3051///
3052/// ```test_harness,no_run
3053/// # extern crate hyper;
3054/// # extern crate hyper_rustls;
3055/// # extern crate google_cloudshell1 as cloudshell1;
3056/// # async fn dox() {
3057/// # use cloudshell1::{CloudShell, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
3058///
3059/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
3060/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
3061/// # .with_native_roots()
3062/// # .unwrap()
3063/// # .https_only()
3064/// # .enable_http2()
3065/// # .build();
3066///
3067/// # let executor = hyper_util::rt::TokioExecutor::new();
3068/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
3069/// # secret,
3070/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
3071/// # yup_oauth2::client::CustomHyperClientBuilder::from(
3072/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
3073/// # ),
3074/// # ).build().await.unwrap();
3075///
3076/// # let client = hyper_util::client::legacy::Client::builder(
3077/// # hyper_util::rt::TokioExecutor::new()
3078/// # )
3079/// # .build(
3080/// # hyper_rustls::HttpsConnectorBuilder::new()
3081/// # .with_native_roots()
3082/// # .unwrap()
3083/// # .https_or_http()
3084/// # .enable_http2()
3085/// # .build()
3086/// # );
3087/// # let mut hub = CloudShell::new(client, auth);
3088/// // You can configure optional parameters by calling the respective setters at will, and
3089/// // execute the final call using `doit()`.
3090/// // Values shown here are possibly random and not representative !
3091/// let result = hub.users().environments_get("name")
3092/// .doit().await;
3093/// # }
3094/// ```
3095pub struct UserEnvironmentGetCall<'a, C>
3096where
3097 C: 'a,
3098{
3099 hub: &'a CloudShell<C>,
3100 _name: String,
3101 _delegate: Option<&'a mut dyn common::Delegate>,
3102 _additional_params: HashMap<String, String>,
3103 _scopes: BTreeSet<String>,
3104}
3105
3106impl<'a, C> common::CallBuilder for UserEnvironmentGetCall<'a, C> {}
3107
3108impl<'a, C> UserEnvironmentGetCall<'a, C>
3109where
3110 C: common::Connector,
3111{
3112 /// Perform the operation you have build so far.
3113 pub async fn doit(mut self) -> common::Result<(common::Response, Environment)> {
3114 use std::borrow::Cow;
3115 use std::io::{Read, Seek};
3116
3117 use common::{url::Params, ToParts};
3118 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
3119
3120 let mut dd = common::DefaultDelegate;
3121 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
3122 dlg.begin(common::MethodInfo {
3123 id: "cloudshell.users.environments.get",
3124 http_method: hyper::Method::GET,
3125 });
3126
3127 for &field in ["alt", "name"].iter() {
3128 if self._additional_params.contains_key(field) {
3129 dlg.finished(false);
3130 return Err(common::Error::FieldClash(field));
3131 }
3132 }
3133
3134 let mut params = Params::with_capacity(3 + self._additional_params.len());
3135 params.push("name", self._name);
3136
3137 params.extend(self._additional_params.iter());
3138
3139 params.push("alt", "json");
3140 let mut url = self.hub._base_url.clone() + "v1/{+name}";
3141 if self._scopes.is_empty() {
3142 self._scopes
3143 .insert(Scope::CloudPlatform.as_ref().to_string());
3144 }
3145
3146 #[allow(clippy::single_element_loop)]
3147 for &(find_this, param_name) in [("{+name}", "name")].iter() {
3148 url = params.uri_replacement(url, param_name, find_this, true);
3149 }
3150 {
3151 let to_remove = ["name"];
3152 params.remove_params(&to_remove);
3153 }
3154
3155 let url = params.parse_with_url(&url);
3156
3157 loop {
3158 let token = match self
3159 .hub
3160 .auth
3161 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
3162 .await
3163 {
3164 Ok(token) => token,
3165 Err(e) => match dlg.token(e) {
3166 Ok(token) => token,
3167 Err(e) => {
3168 dlg.finished(false);
3169 return Err(common::Error::MissingToken(e));
3170 }
3171 },
3172 };
3173 let mut req_result = {
3174 let client = &self.hub.client;
3175 dlg.pre_request();
3176 let mut req_builder = hyper::Request::builder()
3177 .method(hyper::Method::GET)
3178 .uri(url.as_str())
3179 .header(USER_AGENT, self.hub._user_agent.clone());
3180
3181 if let Some(token) = token.as_ref() {
3182 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
3183 }
3184
3185 let request = req_builder
3186 .header(CONTENT_LENGTH, 0_u64)
3187 .body(common::to_body::<String>(None));
3188
3189 client.request(request.unwrap()).await
3190 };
3191
3192 match req_result {
3193 Err(err) => {
3194 if let common::Retry::After(d) = dlg.http_error(&err) {
3195 sleep(d).await;
3196 continue;
3197 }
3198 dlg.finished(false);
3199 return Err(common::Error::HttpError(err));
3200 }
3201 Ok(res) => {
3202 let (mut parts, body) = res.into_parts();
3203 let mut body = common::Body::new(body);
3204 if !parts.status.is_success() {
3205 let bytes = common::to_bytes(body).await.unwrap_or_default();
3206 let error = serde_json::from_str(&common::to_string(&bytes));
3207 let response = common::to_response(parts, bytes.into());
3208
3209 if let common::Retry::After(d) =
3210 dlg.http_failure(&response, error.as_ref().ok())
3211 {
3212 sleep(d).await;
3213 continue;
3214 }
3215
3216 dlg.finished(false);
3217
3218 return Err(match error {
3219 Ok(value) => common::Error::BadRequest(value),
3220 _ => common::Error::Failure(response),
3221 });
3222 }
3223 let response = {
3224 let bytes = common::to_bytes(body).await.unwrap_or_default();
3225 let encoded = common::to_string(&bytes);
3226 match serde_json::from_str(&encoded) {
3227 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
3228 Err(error) => {
3229 dlg.response_json_decode_error(&encoded, &error);
3230 return Err(common::Error::JsonDecodeError(
3231 encoded.to_string(),
3232 error,
3233 ));
3234 }
3235 }
3236 };
3237
3238 dlg.finished(true);
3239 return Ok(response);
3240 }
3241 }
3242 }
3243 }
3244
3245 /// Required. Name of the requested resource, for example `users/me/environments/default` or `users/someone@example.com/environments/default`.
3246 ///
3247 /// Sets the *name* path property to the given value.
3248 ///
3249 /// Even though the property as already been set when instantiating this call,
3250 /// we provide this method for API completeness.
3251 pub fn name(mut self, new_value: &str) -> UserEnvironmentGetCall<'a, C> {
3252 self._name = new_value.to_string();
3253 self
3254 }
3255 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
3256 /// while executing the actual API request.
3257 ///
3258 /// ````text
3259 /// It should be used to handle progress information, and to implement a certain level of resilience.
3260 /// ````
3261 ///
3262 /// Sets the *delegate* property to the given value.
3263 pub fn delegate(
3264 mut self,
3265 new_value: &'a mut dyn common::Delegate,
3266 ) -> UserEnvironmentGetCall<'a, C> {
3267 self._delegate = Some(new_value);
3268 self
3269 }
3270
3271 /// Set any additional parameter of the query string used in the request.
3272 /// It should be used to set parameters which are not yet available through their own
3273 /// setters.
3274 ///
3275 /// Please note that this method must not be used to set any of the known parameters
3276 /// which have their own setter method. If done anyway, the request will fail.
3277 ///
3278 /// # Additional Parameters
3279 ///
3280 /// * *$.xgafv* (query-string) - V1 error format.
3281 /// * *access_token* (query-string) - OAuth access token.
3282 /// * *alt* (query-string) - Data format for response.
3283 /// * *callback* (query-string) - JSONP
3284 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
3285 /// * *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.
3286 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
3287 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
3288 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
3289 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
3290 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
3291 pub fn param<T>(mut self, name: T, value: T) -> UserEnvironmentGetCall<'a, C>
3292 where
3293 T: AsRef<str>,
3294 {
3295 self._additional_params
3296 .insert(name.as_ref().to_string(), value.as_ref().to_string());
3297 self
3298 }
3299
3300 /// Identifies the authorization scope for the method you are building.
3301 ///
3302 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
3303 /// [`Scope::CloudPlatform`].
3304 ///
3305 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
3306 /// tokens for more than one scope.
3307 ///
3308 /// Usually there is more than one suitable scope to authorize an operation, some of which may
3309 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
3310 /// sufficient, a read-write scope will do as well.
3311 pub fn add_scope<St>(mut self, scope: St) -> UserEnvironmentGetCall<'a, C>
3312 where
3313 St: AsRef<str>,
3314 {
3315 self._scopes.insert(String::from(scope.as_ref()));
3316 self
3317 }
3318 /// Identifies the authorization scope(s) for the method you are building.
3319 ///
3320 /// See [`Self::add_scope()`] for details.
3321 pub fn add_scopes<I, St>(mut self, scopes: I) -> UserEnvironmentGetCall<'a, C>
3322 where
3323 I: IntoIterator<Item = St>,
3324 St: AsRef<str>,
3325 {
3326 self._scopes
3327 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
3328 self
3329 }
3330
3331 /// Removes all scopes, and no default scope will be used either.
3332 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
3333 /// for details).
3334 pub fn clear_scopes(mut self) -> UserEnvironmentGetCall<'a, C> {
3335 self._scopes.clear();
3336 self
3337 }
3338}
3339
3340/// Removes a public SSH key from an environment. Clients will no longer be able to connect to the environment using the corresponding private key. If a key with the same content is not present, this will error with NOT_FOUND.
3341///
3342/// A builder for the *environments.removePublicKey* method supported by a *user* resource.
3343/// It is not used directly, but through a [`UserMethods`] instance.
3344///
3345/// # Example
3346///
3347/// Instantiate a resource method builder
3348///
3349/// ```test_harness,no_run
3350/// # extern crate hyper;
3351/// # extern crate hyper_rustls;
3352/// # extern crate google_cloudshell1 as cloudshell1;
3353/// use cloudshell1::api::RemovePublicKeyRequest;
3354/// # async fn dox() {
3355/// # use cloudshell1::{CloudShell, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
3356///
3357/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
3358/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
3359/// # .with_native_roots()
3360/// # .unwrap()
3361/// # .https_only()
3362/// # .enable_http2()
3363/// # .build();
3364///
3365/// # let executor = hyper_util::rt::TokioExecutor::new();
3366/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
3367/// # secret,
3368/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
3369/// # yup_oauth2::client::CustomHyperClientBuilder::from(
3370/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
3371/// # ),
3372/// # ).build().await.unwrap();
3373///
3374/// # let client = hyper_util::client::legacy::Client::builder(
3375/// # hyper_util::rt::TokioExecutor::new()
3376/// # )
3377/// # .build(
3378/// # hyper_rustls::HttpsConnectorBuilder::new()
3379/// # .with_native_roots()
3380/// # .unwrap()
3381/// # .https_or_http()
3382/// # .enable_http2()
3383/// # .build()
3384/// # );
3385/// # let mut hub = CloudShell::new(client, auth);
3386/// // As the method needs a request, you would usually fill it with the desired information
3387/// // into the respective structure. Some of the parts shown here might not be applicable !
3388/// // Values shown here are possibly random and not representative !
3389/// let mut req = RemovePublicKeyRequest::default();
3390///
3391/// // You can configure optional parameters by calling the respective setters at will, and
3392/// // execute the final call using `doit()`.
3393/// // Values shown here are possibly random and not representative !
3394/// let result = hub.users().environments_remove_public_key(req, "environment")
3395/// .doit().await;
3396/// # }
3397/// ```
3398pub struct UserEnvironmentRemovePublicKeyCall<'a, C>
3399where
3400 C: 'a,
3401{
3402 hub: &'a CloudShell<C>,
3403 _request: RemovePublicKeyRequest,
3404 _environment: String,
3405 _delegate: Option<&'a mut dyn common::Delegate>,
3406 _additional_params: HashMap<String, String>,
3407 _scopes: BTreeSet<String>,
3408}
3409
3410impl<'a, C> common::CallBuilder for UserEnvironmentRemovePublicKeyCall<'a, C> {}
3411
3412impl<'a, C> UserEnvironmentRemovePublicKeyCall<'a, C>
3413where
3414 C: common::Connector,
3415{
3416 /// Perform the operation you have build so far.
3417 pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
3418 use std::borrow::Cow;
3419 use std::io::{Read, Seek};
3420
3421 use common::{url::Params, ToParts};
3422 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
3423
3424 let mut dd = common::DefaultDelegate;
3425 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
3426 dlg.begin(common::MethodInfo {
3427 id: "cloudshell.users.environments.removePublicKey",
3428 http_method: hyper::Method::POST,
3429 });
3430
3431 for &field in ["alt", "environment"].iter() {
3432 if self._additional_params.contains_key(field) {
3433 dlg.finished(false);
3434 return Err(common::Error::FieldClash(field));
3435 }
3436 }
3437
3438 let mut params = Params::with_capacity(4 + self._additional_params.len());
3439 params.push("environment", self._environment);
3440
3441 params.extend(self._additional_params.iter());
3442
3443 params.push("alt", "json");
3444 let mut url = self.hub._base_url.clone() + "v1/{+environment}:removePublicKey";
3445 if self._scopes.is_empty() {
3446 self._scopes
3447 .insert(Scope::CloudPlatform.as_ref().to_string());
3448 }
3449
3450 #[allow(clippy::single_element_loop)]
3451 for &(find_this, param_name) in [("{+environment}", "environment")].iter() {
3452 url = params.uri_replacement(url, param_name, find_this, true);
3453 }
3454 {
3455 let to_remove = ["environment"];
3456 params.remove_params(&to_remove);
3457 }
3458
3459 let url = params.parse_with_url(&url);
3460
3461 let mut json_mime_type = mime::APPLICATION_JSON;
3462 let mut request_value_reader = {
3463 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
3464 common::remove_json_null_values(&mut value);
3465 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
3466 serde_json::to_writer(&mut dst, &value).unwrap();
3467 dst
3468 };
3469 let request_size = request_value_reader
3470 .seek(std::io::SeekFrom::End(0))
3471 .unwrap();
3472 request_value_reader
3473 .seek(std::io::SeekFrom::Start(0))
3474 .unwrap();
3475
3476 loop {
3477 let token = match self
3478 .hub
3479 .auth
3480 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
3481 .await
3482 {
3483 Ok(token) => token,
3484 Err(e) => match dlg.token(e) {
3485 Ok(token) => token,
3486 Err(e) => {
3487 dlg.finished(false);
3488 return Err(common::Error::MissingToken(e));
3489 }
3490 },
3491 };
3492 request_value_reader
3493 .seek(std::io::SeekFrom::Start(0))
3494 .unwrap();
3495 let mut req_result = {
3496 let client = &self.hub.client;
3497 dlg.pre_request();
3498 let mut req_builder = hyper::Request::builder()
3499 .method(hyper::Method::POST)
3500 .uri(url.as_str())
3501 .header(USER_AGENT, self.hub._user_agent.clone());
3502
3503 if let Some(token) = token.as_ref() {
3504 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
3505 }
3506
3507 let request = req_builder
3508 .header(CONTENT_TYPE, json_mime_type.to_string())
3509 .header(CONTENT_LENGTH, request_size as u64)
3510 .body(common::to_body(
3511 request_value_reader.get_ref().clone().into(),
3512 ));
3513
3514 client.request(request.unwrap()).await
3515 };
3516
3517 match req_result {
3518 Err(err) => {
3519 if let common::Retry::After(d) = dlg.http_error(&err) {
3520 sleep(d).await;
3521 continue;
3522 }
3523 dlg.finished(false);
3524 return Err(common::Error::HttpError(err));
3525 }
3526 Ok(res) => {
3527 let (mut parts, body) = res.into_parts();
3528 let mut body = common::Body::new(body);
3529 if !parts.status.is_success() {
3530 let bytes = common::to_bytes(body).await.unwrap_or_default();
3531 let error = serde_json::from_str(&common::to_string(&bytes));
3532 let response = common::to_response(parts, bytes.into());
3533
3534 if let common::Retry::After(d) =
3535 dlg.http_failure(&response, error.as_ref().ok())
3536 {
3537 sleep(d).await;
3538 continue;
3539 }
3540
3541 dlg.finished(false);
3542
3543 return Err(match error {
3544 Ok(value) => common::Error::BadRequest(value),
3545 _ => common::Error::Failure(response),
3546 });
3547 }
3548 let response = {
3549 let bytes = common::to_bytes(body).await.unwrap_or_default();
3550 let encoded = common::to_string(&bytes);
3551 match serde_json::from_str(&encoded) {
3552 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
3553 Err(error) => {
3554 dlg.response_json_decode_error(&encoded, &error);
3555 return Err(common::Error::JsonDecodeError(
3556 encoded.to_string(),
3557 error,
3558 ));
3559 }
3560 }
3561 };
3562
3563 dlg.finished(true);
3564 return Ok(response);
3565 }
3566 }
3567 }
3568 }
3569
3570 ///
3571 /// Sets the *request* property to the given value.
3572 ///
3573 /// Even though the property as already been set when instantiating this call,
3574 /// we provide this method for API completeness.
3575 pub fn request(
3576 mut self,
3577 new_value: RemovePublicKeyRequest,
3578 ) -> UserEnvironmentRemovePublicKeyCall<'a, C> {
3579 self._request = new_value;
3580 self
3581 }
3582 /// Environment this key should be removed from, e.g. `users/me/environments/default`.
3583 ///
3584 /// Sets the *environment* path property to the given value.
3585 ///
3586 /// Even though the property as already been set when instantiating this call,
3587 /// we provide this method for API completeness.
3588 pub fn environment(mut self, new_value: &str) -> UserEnvironmentRemovePublicKeyCall<'a, C> {
3589 self._environment = new_value.to_string();
3590 self
3591 }
3592 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
3593 /// while executing the actual API request.
3594 ///
3595 /// ````text
3596 /// It should be used to handle progress information, and to implement a certain level of resilience.
3597 /// ````
3598 ///
3599 /// Sets the *delegate* property to the given value.
3600 pub fn delegate(
3601 mut self,
3602 new_value: &'a mut dyn common::Delegate,
3603 ) -> UserEnvironmentRemovePublicKeyCall<'a, C> {
3604 self._delegate = Some(new_value);
3605 self
3606 }
3607
3608 /// Set any additional parameter of the query string used in the request.
3609 /// It should be used to set parameters which are not yet available through their own
3610 /// setters.
3611 ///
3612 /// Please note that this method must not be used to set any of the known parameters
3613 /// which have their own setter method. If done anyway, the request will fail.
3614 ///
3615 /// # Additional Parameters
3616 ///
3617 /// * *$.xgafv* (query-string) - V1 error format.
3618 /// * *access_token* (query-string) - OAuth access token.
3619 /// * *alt* (query-string) - Data format for response.
3620 /// * *callback* (query-string) - JSONP
3621 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
3622 /// * *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.
3623 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
3624 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
3625 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
3626 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
3627 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
3628 pub fn param<T>(mut self, name: T, value: T) -> UserEnvironmentRemovePublicKeyCall<'a, C>
3629 where
3630 T: AsRef<str>,
3631 {
3632 self._additional_params
3633 .insert(name.as_ref().to_string(), value.as_ref().to_string());
3634 self
3635 }
3636
3637 /// Identifies the authorization scope for the method you are building.
3638 ///
3639 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
3640 /// [`Scope::CloudPlatform`].
3641 ///
3642 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
3643 /// tokens for more than one scope.
3644 ///
3645 /// Usually there is more than one suitable scope to authorize an operation, some of which may
3646 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
3647 /// sufficient, a read-write scope will do as well.
3648 pub fn add_scope<St>(mut self, scope: St) -> UserEnvironmentRemovePublicKeyCall<'a, C>
3649 where
3650 St: AsRef<str>,
3651 {
3652 self._scopes.insert(String::from(scope.as_ref()));
3653 self
3654 }
3655 /// Identifies the authorization scope(s) for the method you are building.
3656 ///
3657 /// See [`Self::add_scope()`] for details.
3658 pub fn add_scopes<I, St>(mut self, scopes: I) -> UserEnvironmentRemovePublicKeyCall<'a, C>
3659 where
3660 I: IntoIterator<Item = St>,
3661 St: AsRef<str>,
3662 {
3663 self._scopes
3664 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
3665 self
3666 }
3667
3668 /// Removes all scopes, and no default scope will be used either.
3669 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
3670 /// for details).
3671 pub fn clear_scopes(mut self) -> UserEnvironmentRemovePublicKeyCall<'a, C> {
3672 self._scopes.clear();
3673 self
3674 }
3675}
3676
3677/// Starts an existing environment, allowing clients to connect to it. The returned operation will contain an instance of StartEnvironmentMetadata in its metadata field. Users can wait for the environment to start by polling this operation via GetOperation. Once the environment has finished starting and is ready to accept connections, the operation will contain a StartEnvironmentResponse in its response field.
3678///
3679/// A builder for the *environments.start* method supported by a *user* resource.
3680/// It is not used directly, but through a [`UserMethods`] instance.
3681///
3682/// # Example
3683///
3684/// Instantiate a resource method builder
3685///
3686/// ```test_harness,no_run
3687/// # extern crate hyper;
3688/// # extern crate hyper_rustls;
3689/// # extern crate google_cloudshell1 as cloudshell1;
3690/// use cloudshell1::api::StartEnvironmentRequest;
3691/// # async fn dox() {
3692/// # use cloudshell1::{CloudShell, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
3693///
3694/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
3695/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
3696/// # .with_native_roots()
3697/// # .unwrap()
3698/// # .https_only()
3699/// # .enable_http2()
3700/// # .build();
3701///
3702/// # let executor = hyper_util::rt::TokioExecutor::new();
3703/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
3704/// # secret,
3705/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
3706/// # yup_oauth2::client::CustomHyperClientBuilder::from(
3707/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
3708/// # ),
3709/// # ).build().await.unwrap();
3710///
3711/// # let client = hyper_util::client::legacy::Client::builder(
3712/// # hyper_util::rt::TokioExecutor::new()
3713/// # )
3714/// # .build(
3715/// # hyper_rustls::HttpsConnectorBuilder::new()
3716/// # .with_native_roots()
3717/// # .unwrap()
3718/// # .https_or_http()
3719/// # .enable_http2()
3720/// # .build()
3721/// # );
3722/// # let mut hub = CloudShell::new(client, auth);
3723/// // As the method needs a request, you would usually fill it with the desired information
3724/// // into the respective structure. Some of the parts shown here might not be applicable !
3725/// // Values shown here are possibly random and not representative !
3726/// let mut req = StartEnvironmentRequest::default();
3727///
3728/// // You can configure optional parameters by calling the respective setters at will, and
3729/// // execute the final call using `doit()`.
3730/// // Values shown here are possibly random and not representative !
3731/// let result = hub.users().environments_start(req, "name")
3732/// .doit().await;
3733/// # }
3734/// ```
3735pub struct UserEnvironmentStartCall<'a, C>
3736where
3737 C: 'a,
3738{
3739 hub: &'a CloudShell<C>,
3740 _request: StartEnvironmentRequest,
3741 _name: String,
3742 _delegate: Option<&'a mut dyn common::Delegate>,
3743 _additional_params: HashMap<String, String>,
3744 _scopes: BTreeSet<String>,
3745}
3746
3747impl<'a, C> common::CallBuilder for UserEnvironmentStartCall<'a, C> {}
3748
3749impl<'a, C> UserEnvironmentStartCall<'a, C>
3750where
3751 C: common::Connector,
3752{
3753 /// Perform the operation you have build so far.
3754 pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
3755 use std::borrow::Cow;
3756 use std::io::{Read, Seek};
3757
3758 use common::{url::Params, ToParts};
3759 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
3760
3761 let mut dd = common::DefaultDelegate;
3762 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
3763 dlg.begin(common::MethodInfo {
3764 id: "cloudshell.users.environments.start",
3765 http_method: hyper::Method::POST,
3766 });
3767
3768 for &field in ["alt", "name"].iter() {
3769 if self._additional_params.contains_key(field) {
3770 dlg.finished(false);
3771 return Err(common::Error::FieldClash(field));
3772 }
3773 }
3774
3775 let mut params = Params::with_capacity(4 + self._additional_params.len());
3776 params.push("name", self._name);
3777
3778 params.extend(self._additional_params.iter());
3779
3780 params.push("alt", "json");
3781 let mut url = self.hub._base_url.clone() + "v1/{+name}:start";
3782 if self._scopes.is_empty() {
3783 self._scopes
3784 .insert(Scope::CloudPlatform.as_ref().to_string());
3785 }
3786
3787 #[allow(clippy::single_element_loop)]
3788 for &(find_this, param_name) in [("{+name}", "name")].iter() {
3789 url = params.uri_replacement(url, param_name, find_this, true);
3790 }
3791 {
3792 let to_remove = ["name"];
3793 params.remove_params(&to_remove);
3794 }
3795
3796 let url = params.parse_with_url(&url);
3797
3798 let mut json_mime_type = mime::APPLICATION_JSON;
3799 let mut request_value_reader = {
3800 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
3801 common::remove_json_null_values(&mut value);
3802 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
3803 serde_json::to_writer(&mut dst, &value).unwrap();
3804 dst
3805 };
3806 let request_size = request_value_reader
3807 .seek(std::io::SeekFrom::End(0))
3808 .unwrap();
3809 request_value_reader
3810 .seek(std::io::SeekFrom::Start(0))
3811 .unwrap();
3812
3813 loop {
3814 let token = match self
3815 .hub
3816 .auth
3817 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
3818 .await
3819 {
3820 Ok(token) => token,
3821 Err(e) => match dlg.token(e) {
3822 Ok(token) => token,
3823 Err(e) => {
3824 dlg.finished(false);
3825 return Err(common::Error::MissingToken(e));
3826 }
3827 },
3828 };
3829 request_value_reader
3830 .seek(std::io::SeekFrom::Start(0))
3831 .unwrap();
3832 let mut req_result = {
3833 let client = &self.hub.client;
3834 dlg.pre_request();
3835 let mut req_builder = hyper::Request::builder()
3836 .method(hyper::Method::POST)
3837 .uri(url.as_str())
3838 .header(USER_AGENT, self.hub._user_agent.clone());
3839
3840 if let Some(token) = token.as_ref() {
3841 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
3842 }
3843
3844 let request = req_builder
3845 .header(CONTENT_TYPE, json_mime_type.to_string())
3846 .header(CONTENT_LENGTH, request_size as u64)
3847 .body(common::to_body(
3848 request_value_reader.get_ref().clone().into(),
3849 ));
3850
3851 client.request(request.unwrap()).await
3852 };
3853
3854 match req_result {
3855 Err(err) => {
3856 if let common::Retry::After(d) = dlg.http_error(&err) {
3857 sleep(d).await;
3858 continue;
3859 }
3860 dlg.finished(false);
3861 return Err(common::Error::HttpError(err));
3862 }
3863 Ok(res) => {
3864 let (mut parts, body) = res.into_parts();
3865 let mut body = common::Body::new(body);
3866 if !parts.status.is_success() {
3867 let bytes = common::to_bytes(body).await.unwrap_or_default();
3868 let error = serde_json::from_str(&common::to_string(&bytes));
3869 let response = common::to_response(parts, bytes.into());
3870
3871 if let common::Retry::After(d) =
3872 dlg.http_failure(&response, error.as_ref().ok())
3873 {
3874 sleep(d).await;
3875 continue;
3876 }
3877
3878 dlg.finished(false);
3879
3880 return Err(match error {
3881 Ok(value) => common::Error::BadRequest(value),
3882 _ => common::Error::Failure(response),
3883 });
3884 }
3885 let response = {
3886 let bytes = common::to_bytes(body).await.unwrap_or_default();
3887 let encoded = common::to_string(&bytes);
3888 match serde_json::from_str(&encoded) {
3889 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
3890 Err(error) => {
3891 dlg.response_json_decode_error(&encoded, &error);
3892 return Err(common::Error::JsonDecodeError(
3893 encoded.to_string(),
3894 error,
3895 ));
3896 }
3897 }
3898 };
3899
3900 dlg.finished(true);
3901 return Ok(response);
3902 }
3903 }
3904 }
3905 }
3906
3907 ///
3908 /// Sets the *request* property to the given value.
3909 ///
3910 /// Even though the property as already been set when instantiating this call,
3911 /// we provide this method for API completeness.
3912 pub fn request(
3913 mut self,
3914 new_value: StartEnvironmentRequest,
3915 ) -> UserEnvironmentStartCall<'a, C> {
3916 self._request = new_value;
3917 self
3918 }
3919 /// Name of the resource that should be started, for example `users/me/environments/default` or `users/someone@example.com/environments/default`.
3920 ///
3921 /// Sets the *name* path property to the given value.
3922 ///
3923 /// Even though the property as already been set when instantiating this call,
3924 /// we provide this method for API completeness.
3925 pub fn name(mut self, new_value: &str) -> UserEnvironmentStartCall<'a, C> {
3926 self._name = new_value.to_string();
3927 self
3928 }
3929 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
3930 /// while executing the actual API request.
3931 ///
3932 /// ````text
3933 /// It should be used to handle progress information, and to implement a certain level of resilience.
3934 /// ````
3935 ///
3936 /// Sets the *delegate* property to the given value.
3937 pub fn delegate(
3938 mut self,
3939 new_value: &'a mut dyn common::Delegate,
3940 ) -> UserEnvironmentStartCall<'a, C> {
3941 self._delegate = Some(new_value);
3942 self
3943 }
3944
3945 /// Set any additional parameter of the query string used in the request.
3946 /// It should be used to set parameters which are not yet available through their own
3947 /// setters.
3948 ///
3949 /// Please note that this method must not be used to set any of the known parameters
3950 /// which have their own setter method. If done anyway, the request will fail.
3951 ///
3952 /// # Additional Parameters
3953 ///
3954 /// * *$.xgafv* (query-string) - V1 error format.
3955 /// * *access_token* (query-string) - OAuth access token.
3956 /// * *alt* (query-string) - Data format for response.
3957 /// * *callback* (query-string) - JSONP
3958 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
3959 /// * *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.
3960 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
3961 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
3962 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
3963 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
3964 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
3965 pub fn param<T>(mut self, name: T, value: T) -> UserEnvironmentStartCall<'a, C>
3966 where
3967 T: AsRef<str>,
3968 {
3969 self._additional_params
3970 .insert(name.as_ref().to_string(), value.as_ref().to_string());
3971 self
3972 }
3973
3974 /// Identifies the authorization scope for the method you are building.
3975 ///
3976 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
3977 /// [`Scope::CloudPlatform`].
3978 ///
3979 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
3980 /// tokens for more than one scope.
3981 ///
3982 /// Usually there is more than one suitable scope to authorize an operation, some of which may
3983 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
3984 /// sufficient, a read-write scope will do as well.
3985 pub fn add_scope<St>(mut self, scope: St) -> UserEnvironmentStartCall<'a, C>
3986 where
3987 St: AsRef<str>,
3988 {
3989 self._scopes.insert(String::from(scope.as_ref()));
3990 self
3991 }
3992 /// Identifies the authorization scope(s) for the method you are building.
3993 ///
3994 /// See [`Self::add_scope()`] for details.
3995 pub fn add_scopes<I, St>(mut self, scopes: I) -> UserEnvironmentStartCall<'a, C>
3996 where
3997 I: IntoIterator<Item = St>,
3998 St: AsRef<str>,
3999 {
4000 self._scopes
4001 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
4002 self
4003 }
4004
4005 /// Removes all scopes, and no default scope will be used either.
4006 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
4007 /// for details).
4008 pub fn clear_scopes(mut self) -> UserEnvironmentStartCall<'a, C> {
4009 self._scopes.clear();
4010 self
4011 }
4012}