google_gmail1/
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    /// Read, compose, send, and permanently delete all your email from Gmail
17    Gmai,
18
19    /// Manage drafts and send emails when you interact with the add-on
20    AddonCurrentActionCompose,
21
22    /// View your email messages when you interact with the add-on
23    AddonCurrentMessageAction,
24
25    /// View your email message metadata when the add-on is running
26    AddonCurrentMessageMetadata,
27
28    /// View your email messages when the add-on is running
29    AddonCurrentMessageReadonly,
30
31    /// Manage drafts and send emails
32    Compose,
33
34    /// Add emails into your Gmail mailbox
35    Insert,
36
37    /// See and edit your email labels
38    Label,
39
40    /// View your email message metadata such as labels and headers, but not the email body
41    Metadata,
42
43    /// Read, compose, and send emails from your Gmail account
44    Modify,
45
46    /// View your email messages and settings
47    Readonly,
48
49    /// Send email on your behalf
50    Send,
51
52    /// See, edit, create, or change your email settings and filters in Gmail
53    SettingBasic,
54
55    /// Manage your sensitive mail settings, including who can manage your mail
56    SettingSharing,
57}
58
59impl AsRef<str> for Scope {
60    fn as_ref(&self) -> &str {
61        match *self {
62            Scope::Gmai => "https://mail.google.com/",
63            Scope::AddonCurrentActionCompose => {
64                "https://www.googleapis.com/auth/gmail.addons.current.action.compose"
65            }
66            Scope::AddonCurrentMessageAction => {
67                "https://www.googleapis.com/auth/gmail.addons.current.message.action"
68            }
69            Scope::AddonCurrentMessageMetadata => {
70                "https://www.googleapis.com/auth/gmail.addons.current.message.metadata"
71            }
72            Scope::AddonCurrentMessageReadonly => {
73                "https://www.googleapis.com/auth/gmail.addons.current.message.readonly"
74            }
75            Scope::Compose => "https://www.googleapis.com/auth/gmail.compose",
76            Scope::Insert => "https://www.googleapis.com/auth/gmail.insert",
77            Scope::Label => "https://www.googleapis.com/auth/gmail.labels",
78            Scope::Metadata => "https://www.googleapis.com/auth/gmail.metadata",
79            Scope::Modify => "https://www.googleapis.com/auth/gmail.modify",
80            Scope::Readonly => "https://www.googleapis.com/auth/gmail.readonly",
81            Scope::Send => "https://www.googleapis.com/auth/gmail.send",
82            Scope::SettingBasic => "https://www.googleapis.com/auth/gmail.settings.basic",
83            Scope::SettingSharing => "https://www.googleapis.com/auth/gmail.settings.sharing",
84        }
85    }
86}
87
88#[allow(clippy::derivable_impls)]
89impl Default for Scope {
90    fn default() -> Scope {
91        Scope::AddonCurrentMessageReadonly
92    }
93}
94
95// ########
96// HUB ###
97// ######
98
99/// Central instance to access all Gmail related resource activities
100///
101/// # Examples
102///
103/// Instantiate a new hub
104///
105/// ```test_harness,no_run
106/// extern crate hyper;
107/// extern crate hyper_rustls;
108/// extern crate google_gmail1 as gmail1;
109/// use gmail1::api::Message;
110/// use gmail1::{Result, Error};
111/// use std::fs;
112/// # async fn dox() {
113/// use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
114///
115/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
116/// // `client_secret`, among other things.
117/// let secret: yup_oauth2::ApplicationSecret = Default::default();
118/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
119/// // unless you replace  `None` with the desired Flow.
120/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
121/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
122/// // retrieve them from storage.
123/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
124///     secret,
125///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
126/// ).build().await.unwrap();
127///
128/// let client = hyper_util::client::legacy::Client::builder(
129///     hyper_util::rt::TokioExecutor::new()
130/// )
131/// .build(
132///     hyper_rustls::HttpsConnectorBuilder::new()
133///         .with_native_roots()
134///         .unwrap()
135///         .https_or_http()
136///         .enable_http1()
137///         .build()
138/// );
139/// let mut hub = Gmail::new(client, auth);
140/// // As the method needs a request, you would usually fill it with the desired information
141/// // into the respective structure. Some of the parts shown here might not be applicable !
142/// // Values shown here are possibly random and not representative !
143/// let mut req = Message::default();
144///
145/// // You can configure optional parameters by calling the respective setters at will, and
146/// // execute the final call using `upload_resumable(...)`.
147/// // Values shown here are possibly random and not representative !
148/// let result = hub.users().messages_import(req, "userId")
149///              .process_for_calendar(true)
150///              .never_mark_spam(false)
151///              .internal_date_source("amet")
152///              .deleted(true)
153///              .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()).await;
154///
155/// match result {
156///     Err(e) => match e {
157///         // The Error enum provides details about what exactly happened.
158///         // You can also just use its `Debug`, `Display` or `Error` traits
159///          Error::HttpError(_)
160///         |Error::Io(_)
161///         |Error::MissingAPIKey
162///         |Error::MissingToken(_)
163///         |Error::Cancelled
164///         |Error::UploadSizeLimitExceeded(_, _)
165///         |Error::Failure(_)
166///         |Error::BadRequest(_)
167///         |Error::FieldClash(_)
168///         |Error::JsonDecodeError(_, _) => println!("{}", e),
169///     },
170///     Ok(res) => println!("Success: {:?}", res),
171/// }
172/// # }
173/// ```
174#[derive(Clone)]
175pub struct Gmail<C> {
176    pub client: common::Client<C>,
177    pub auth: Box<dyn common::GetToken>,
178    _user_agent: String,
179    _base_url: String,
180    _root_url: String,
181}
182
183impl<C> common::Hub for Gmail<C> {}
184
185impl<'a, C> Gmail<C> {
186    pub fn new<A: 'static + common::GetToken>(client: common::Client<C>, auth: A) -> Gmail<C> {
187        Gmail {
188            client,
189            auth: Box::new(auth),
190            _user_agent: "google-api-rust-client/6.0.0".to_string(),
191            _base_url: "https://gmail.googleapis.com/".to_string(),
192            _root_url: "https://gmail.googleapis.com/".to_string(),
193        }
194    }
195
196    pub fn users(&'a self) -> UserMethods<'a, C> {
197        UserMethods { hub: self }
198    }
199
200    /// Set the user-agent header field to use in all requests to the server.
201    /// It defaults to `google-api-rust-client/6.0.0`.
202    ///
203    /// Returns the previously set user-agent.
204    pub fn user_agent(&mut self, agent_name: String) -> String {
205        std::mem::replace(&mut self._user_agent, agent_name)
206    }
207
208    /// Set the base url to use in all requests to the server.
209    /// It defaults to `https://gmail.googleapis.com/`.
210    ///
211    /// Returns the previously set base url.
212    pub fn base_url(&mut self, new_base_url: String) -> String {
213        std::mem::replace(&mut self._base_url, new_base_url)
214    }
215
216    /// Set the root url to use in all requests to the server.
217    /// It defaults to `https://gmail.googleapis.com/`.
218    ///
219    /// Returns the previously set root url.
220    pub fn root_url(&mut self, new_root_url: String) -> String {
221        std::mem::replace(&mut self._root_url, new_root_url)
222    }
223}
224
225// ############
226// SCHEMAS ###
227// ##########
228/// Auto-forwarding settings for an account.
229///
230/// # Activities
231///
232/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
233/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
234///
235/// * [settings get auto forwarding users](UserSettingGetAutoForwardingCall) (response)
236/// * [settings update auto forwarding users](UserSettingUpdateAutoForwardingCall) (request|response)
237#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
238#[serde_with::serde_as]
239#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
240pub struct AutoForwarding {
241    /// The state that a message should be left in after it has been forwarded.
242    pub disposition: Option<String>,
243    /// Email address to which all incoming messages are forwarded. This email address must be a verified member of the forwarding addresses.
244    #[serde(rename = "emailAddress")]
245    pub email_address: Option<String>,
246    /// Whether all incoming mail is automatically forwarded to another address.
247    pub enabled: Option<bool>,
248}
249
250impl common::RequestValue for AutoForwarding {}
251impl common::ResponseResult for AutoForwarding {}
252
253/// There is no detailed description.
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/// * [messages batch delete users](UserMessageBatchDeleteCall) (request)
261#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
262#[serde_with::serde_as]
263#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
264pub struct BatchDeleteMessagesRequest {
265    /// The IDs of the messages to delete.
266    pub ids: Option<Vec<String>>,
267}
268
269impl common::RequestValue for BatchDeleteMessagesRequest {}
270
271/// There is no detailed description.
272///
273/// # Activities
274///
275/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
276/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
277///
278/// * [messages batch modify users](UserMessageBatchModifyCall) (request)
279#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
280#[serde_with::serde_as]
281#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
282pub struct BatchModifyMessagesRequest {
283    /// A list of label IDs to add to messages.
284    #[serde(rename = "addLabelIds")]
285    pub add_label_ids: Option<Vec<String>>,
286    /// The IDs of the messages to modify. There is a limit of 1000 ids per request.
287    pub ids: Option<Vec<String>>,
288    /// A list of label IDs to remove from messages.
289    #[serde(rename = "removeLabelIds")]
290    pub remove_label_ids: Option<Vec<String>>,
291}
292
293impl common::RequestValue for BatchModifyMessagesRequest {}
294
295/// The client-side encryption (CSE) configuration for the email address of an authenticated user. Gmail uses CSE configurations to save drafts of client-side encrypted email messages, and to sign and send encrypted email messages.
296///
297/// # Activities
298///
299/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
300/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
301///
302/// * [settings cse identities create users](UserSettingCseIdentityCreateCall) (request|response)
303/// * [settings cse identities get users](UserSettingCseIdentityGetCall) (response)
304/// * [settings cse identities patch users](UserSettingCseIdentityPatchCall) (request|response)
305#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
306#[serde_with::serde_as]
307#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
308pub struct CseIdentity {
309    /// The email address for the sending identity. The email address must be the primary email address of the authenticated user.
310    #[serde(rename = "emailAddress")]
311    pub email_address: Option<String>,
312    /// If a key pair is associated, the ID of the key pair, CseKeyPair.
313    #[serde(rename = "primaryKeyPairId")]
314    pub primary_key_pair_id: Option<String>,
315    /// The configuration of a CSE identity that uses different key pairs for signing and encryption.
316    #[serde(rename = "signAndEncryptKeyPairs")]
317    pub sign_and_encrypt_key_pairs: Option<SignAndEncryptKeyPairs>,
318}
319
320impl common::RequestValue for CseIdentity {}
321impl common::ResponseResult for CseIdentity {}
322
323/// A client-side encryption S/MIME key pair, which is comprised of a public key, its certificate chain, and metadata for its paired private key. Gmail uses the key pair to complete the following tasks: - Sign outgoing client-side encrypted messages. - Save and reopen drafts of client-side encrypted messages. - Save and reopen sent messages. - Decrypt incoming or archived S/MIME messages.
324///
325/// # Activities
326///
327/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
328/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
329///
330/// * [settings cse keypairs create users](UserSettingCseKeypairCreateCall) (request|response)
331/// * [settings cse keypairs disable users](UserSettingCseKeypairDisableCall) (response)
332/// * [settings cse keypairs enable users](UserSettingCseKeypairEnableCall) (response)
333/// * [settings cse keypairs get users](UserSettingCseKeypairGetCall) (response)
334#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
335#[serde_with::serde_as]
336#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
337pub struct CseKeyPair {
338    /// Output only. If a key pair is set to `DISABLED`, the time that the key pair's state changed from `ENABLED` to `DISABLED`. This field is present only when the key pair is in state `DISABLED`.
339    #[serde(rename = "disableTime")]
340    pub disable_time: Option<chrono::DateTime<chrono::offset::Utc>>,
341    /// Output only. The current state of the key pair.
342    #[serde(rename = "enablementState")]
343    pub enablement_state: Option<String>,
344    /// Output only. The immutable ID for the client-side encryption S/MIME key pair.
345    #[serde(rename = "keyPairId")]
346    pub key_pair_id: Option<String>,
347    /// Output only. The public key and its certificate chain, in [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) format.
348    pub pem: Option<String>,
349    /// Input only. The public key and its certificate chain. The chain must be in [PKCS#7](https://en.wikipedia.org/wiki/PKCS_7) format and use PEM encoding and ASCII armor.
350    pub pkcs7: Option<String>,
351    /// Metadata for instances of this key pair's private key.
352    #[serde(rename = "privateKeyMetadata")]
353    pub private_key_metadata: Option<Vec<CsePrivateKeyMetadata>>,
354    /// Output only. The email address identities that are specified on the leaf certificate.
355    #[serde(rename = "subjectEmailAddresses")]
356    pub subject_email_addresses: Option<Vec<String>>,
357}
358
359impl common::RequestValue for CseKeyPair {}
360impl common::ResponseResult for CseKeyPair {}
361
362/// Metadata for a private key instance.
363///
364/// This type is not used in any activity, and only used as *part* of another schema.
365///
366#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
367#[serde_with::serde_as]
368#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
369pub struct CsePrivateKeyMetadata {
370    /// Metadata for hardware keys.
371    #[serde(rename = "hardwareKeyMetadata")]
372    pub hardware_key_metadata: Option<HardwareKeyMetadata>,
373    /// Metadata for a private key instance managed by an external key access control list service.
374    #[serde(rename = "kaclsKeyMetadata")]
375    pub kacls_key_metadata: Option<KaclsKeyMetadata>,
376    /// Output only. The immutable ID for the private key metadata instance.
377    #[serde(rename = "privateKeyMetadataId")]
378    pub private_key_metadata_id: Option<String>,
379}
380
381impl common::Part for CsePrivateKeyMetadata {}
382
383/// Settings for a delegate. Delegates can read, send, and delete messages, as well as view and add contacts, for the delegator’s account. See “Set up mail delegation” for more information about delegates.
384///
385/// # Activities
386///
387/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
388/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
389///
390/// * [settings delegates create users](UserSettingDelegateCreateCall) (request|response)
391/// * [settings delegates get users](UserSettingDelegateGetCall) (response)
392#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
393#[serde_with::serde_as]
394#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
395pub struct Delegate {
396    /// The email address of the delegate.
397    #[serde(rename = "delegateEmail")]
398    pub delegate_email: Option<String>,
399    /// Indicates whether this address has been verified and can act as a delegate for the account. Read-only.
400    #[serde(rename = "verificationStatus")]
401    pub verification_status: Option<String>,
402}
403
404impl common::RequestValue for Delegate {}
405impl common::ResponseResult for Delegate {}
406
407/// Requests to turn off a client-side encryption key pair.
408///
409/// # Activities
410///
411/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
412/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
413///
414/// * [settings cse keypairs disable users](UserSettingCseKeypairDisableCall) (request)
415#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
416#[serde_with::serde_as]
417#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
418pub struct DisableCseKeyPairRequest {
419    _never_set: Option<bool>,
420}
421
422impl common::RequestValue for DisableCseKeyPairRequest {}
423
424/// A draft email in the user’s mailbox.
425///
426/// # Activities
427///
428/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
429/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
430///
431/// * [drafts create users](UserDraftCreateCall) (request|response)
432/// * [drafts get users](UserDraftGetCall) (response)
433/// * [drafts send users](UserDraftSendCall) (request)
434/// * [drafts update users](UserDraftUpdateCall) (request|response)
435#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
436#[serde_with::serde_as]
437#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
438pub struct Draft {
439    /// The immutable ID of the draft.
440    pub id: Option<String>,
441    /// The message content of the draft.
442    pub message: Option<Message>,
443}
444
445impl common::RequestValue for Draft {}
446impl common::ResponseResult for Draft {}
447
448/// Requests to turn on a client-side encryption key pair.
449///
450/// # Activities
451///
452/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
453/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
454///
455/// * [settings cse keypairs enable users](UserSettingCseKeypairEnableCall) (request)
456#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
457#[serde_with::serde_as]
458#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
459pub struct EnableCseKeyPairRequest {
460    _never_set: Option<bool>,
461}
462
463impl common::RequestValue for EnableCseKeyPairRequest {}
464
465/// Resource definition for Gmail filters. Filters apply to specific messages instead of an entire email thread.
466///
467/// # Activities
468///
469/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
470/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
471///
472/// * [settings filters create users](UserSettingFilterCreateCall) (request|response)
473/// * [settings filters get users](UserSettingFilterGetCall) (response)
474#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
475#[serde_with::serde_as]
476#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
477pub struct Filter {
478    /// Action that the filter performs.
479    pub action: Option<FilterAction>,
480    /// Matching criteria for the filter.
481    pub criteria: Option<FilterCriteria>,
482    /// The server assigned ID of the filter.
483    pub id: Option<String>,
484}
485
486impl common::RequestValue for Filter {}
487impl common::ResponseResult for Filter {}
488
489/// A set of actions to perform on a message.
490///
491/// This type is not used in any activity, and only used as *part* of another schema.
492///
493#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
494#[serde_with::serde_as]
495#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
496pub struct FilterAction {
497    /// List of labels to add to the message.
498    #[serde(rename = "addLabelIds")]
499    pub add_label_ids: Option<Vec<String>>,
500    /// Email address that the message should be forwarded to.
501    pub forward: Option<String>,
502    /// List of labels to remove from the message.
503    #[serde(rename = "removeLabelIds")]
504    pub remove_label_ids: Option<Vec<String>>,
505}
506
507impl common::Part for FilterAction {}
508
509/// Message matching criteria.
510///
511/// This type is not used in any activity, and only used as *part* of another schema.
512///
513#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
514#[serde_with::serde_as]
515#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
516pub struct FilterCriteria {
517    /// Whether the response should exclude chats.
518    #[serde(rename = "excludeChats")]
519    pub exclude_chats: Option<bool>,
520    /// The sender's display name or email address.
521    pub from: Option<String>,
522    /// Whether the message has any attachment.
523    #[serde(rename = "hasAttachment")]
524    pub has_attachment: Option<bool>,
525    /// Only return messages not matching the specified query. Supports the same query format as the Gmail search box. For example, `"from:someuser@example.com rfc822msgid: is:unread"`.
526    #[serde(rename = "negatedQuery")]
527    pub negated_query: Option<String>,
528    /// Only return messages matching the specified query. Supports the same query format as the Gmail search box. For example, `"from:someuser@example.com rfc822msgid: is:unread"`.
529    pub query: Option<String>,
530    /// The size of the entire RFC822 message in bytes, including all headers and attachments.
531    pub size: Option<i32>,
532    /// How the message size in bytes should be in relation to the size field.
533    #[serde(rename = "sizeComparison")]
534    pub size_comparison: Option<String>,
535    /// Case-insensitive phrase found in the message's subject. Trailing and leading whitespace are be trimmed and adjacent spaces are collapsed.
536    pub subject: Option<String>,
537    /// The recipient's display name or email address. Includes recipients in the "to", "cc", and "bcc" header fields. You can use simply the local part of the email address. For example, "example" and "example@" both match "example@gmail.com". This field is case-insensitive.
538    pub to: Option<String>,
539}
540
541impl common::Part for FilterCriteria {}
542
543/// Settings for a forwarding address.
544///
545/// # Activities
546///
547/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
548/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
549///
550/// * [settings forwarding addresses create users](UserSettingForwardingAddressCreateCall) (request|response)
551/// * [settings forwarding addresses get users](UserSettingForwardingAddressGetCall) (response)
552#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
553#[serde_with::serde_as]
554#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
555pub struct ForwardingAddress {
556    /// An email address to which messages can be forwarded.
557    #[serde(rename = "forwardingEmail")]
558    pub forwarding_email: Option<String>,
559    /// Indicates whether this address has been verified and is usable for forwarding. Read-only.
560    #[serde(rename = "verificationStatus")]
561    pub verification_status: Option<String>,
562}
563
564impl common::RequestValue for ForwardingAddress {}
565impl common::ResponseResult for ForwardingAddress {}
566
567/// Metadata for hardware keys.
568///
569/// This type is not used in any activity, and only used as *part* of another schema.
570///
571#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
572#[serde_with::serde_as]
573#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
574pub struct HardwareKeyMetadata {
575    /// Description about the hardware key.
576    pub description: Option<String>,
577}
578
579impl common::Part for HardwareKeyMetadata {}
580
581/// A record of a change to the user's mailbox. Each history change may affect multiple messages in multiple ways.
582///
583/// This type is not used in any activity, and only used as *part* of another schema.
584///
585#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
586#[serde_with::serde_as]
587#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
588pub struct History {
589    /// The mailbox sequence ID.
590    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
591    pub id: Option<u64>,
592    /// Labels added to messages in this history record.
593    #[serde(rename = "labelsAdded")]
594    pub labels_added: Option<Vec<HistoryLabelAdded>>,
595    /// Labels removed from messages in this history record.
596    #[serde(rename = "labelsRemoved")]
597    pub labels_removed: Option<Vec<HistoryLabelRemoved>>,
598    /// List of messages changed in this history record. The fields for specific change types, such as `messagesAdded` may duplicate messages in this field. We recommend using the specific change-type fields instead of this.
599    pub messages: Option<Vec<Message>>,
600    /// Messages added to the mailbox in this history record.
601    #[serde(rename = "messagesAdded")]
602    pub messages_added: Option<Vec<HistoryMessageAdded>>,
603    /// Messages deleted (not Trashed) from the mailbox in this history record.
604    #[serde(rename = "messagesDeleted")]
605    pub messages_deleted: Option<Vec<HistoryMessageDeleted>>,
606}
607
608impl common::Part for History {}
609
610/// There is no detailed description.
611///
612/// This type is not used in any activity, and only used as *part* of another schema.
613///
614#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
615#[serde_with::serde_as]
616#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
617pub struct HistoryLabelAdded {
618    /// Label IDs added to the message.
619    #[serde(rename = "labelIds")]
620    pub label_ids: Option<Vec<String>>,
621    /// no description provided
622    pub message: Option<Message>,
623}
624
625impl common::Part for HistoryLabelAdded {}
626
627/// There is no detailed description.
628///
629/// This type is not used in any activity, and only used as *part* of another schema.
630///
631#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
632#[serde_with::serde_as]
633#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
634pub struct HistoryLabelRemoved {
635    /// Label IDs removed from the message.
636    #[serde(rename = "labelIds")]
637    pub label_ids: Option<Vec<String>>,
638    /// no description provided
639    pub message: Option<Message>,
640}
641
642impl common::Part for HistoryLabelRemoved {}
643
644/// There is no detailed description.
645///
646/// This type is not used in any activity, and only used as *part* of another schema.
647///
648#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
649#[serde_with::serde_as]
650#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
651pub struct HistoryMessageAdded {
652    /// no description provided
653    pub message: Option<Message>,
654}
655
656impl common::Part for HistoryMessageAdded {}
657
658/// There is no detailed description.
659///
660/// This type is not used in any activity, and only used as *part* of another schema.
661///
662#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
663#[serde_with::serde_as]
664#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
665pub struct HistoryMessageDeleted {
666    /// no description provided
667    pub message: Option<Message>,
668}
669
670impl common::Part for HistoryMessageDeleted {}
671
672/// IMAP settings for an account.
673///
674/// # Activities
675///
676/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
677/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
678///
679/// * [settings get imap users](UserSettingGetImapCall) (response)
680/// * [settings update imap users](UserSettingUpdateImapCall) (request|response)
681#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
682#[serde_with::serde_as]
683#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
684pub struct ImapSettings {
685    /// If this value is true, Gmail will immediately expunge a message when it is marked as deleted in IMAP. Otherwise, Gmail will wait for an update from the client before expunging messages marked as deleted.
686    #[serde(rename = "autoExpunge")]
687    pub auto_expunge: Option<bool>,
688    /// Whether IMAP is enabled for the account.
689    pub enabled: Option<bool>,
690    /// The action that will be executed on a message when it is marked as deleted and expunged from the last visible IMAP folder.
691    #[serde(rename = "expungeBehavior")]
692    pub expunge_behavior: Option<String>,
693    /// An optional limit on the number of messages that an IMAP folder may contain. Legal values are 0, 1000, 2000, 5000 or 10000. A value of zero is interpreted to mean that there is no limit.
694    #[serde(rename = "maxFolderSize")]
695    pub max_folder_size: Option<i32>,
696}
697
698impl common::RequestValue for ImapSettings {}
699impl common::ResponseResult for ImapSettings {}
700
701/// Metadata for private keys managed by an external key access control list service. For details about managing key access, see [Google Workspace CSE API Reference](https://developers.google.com/workspace/cse/reference).
702///
703/// This type is not used in any activity, and only used as *part* of another schema.
704///
705#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
706#[serde_with::serde_as]
707#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
708pub struct KaclsKeyMetadata {
709    /// Opaque data generated and used by the key access control list service. Maximum size: 8 KiB.
710    #[serde(rename = "kaclsData")]
711    pub kacls_data: Option<String>,
712    /// The URI of the key access control list service that manages the private key.
713    #[serde(rename = "kaclsUri")]
714    pub kacls_uri: Option<String>,
715}
716
717impl common::Part for KaclsKeyMetadata {}
718
719/// Labels are used to categorize messages and threads within the user’s mailbox. The maximum number of labels supported for a user’s mailbox is 10,000.
720///
721/// # Activities
722///
723/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
724/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
725///
726/// * [labels create users](UserLabelCreateCall) (request|response)
727/// * [labels get users](UserLabelGetCall) (response)
728/// * [labels patch users](UserLabelPatchCall) (request|response)
729/// * [labels update users](UserLabelUpdateCall) (request|response)
730#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
731#[serde_with::serde_as]
732#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
733pub struct Label {
734    /// The color to assign to the label. Color is only available for labels that have their `type` set to `user`.
735    pub color: Option<LabelColor>,
736    /// The immutable ID of the label.
737    pub id: Option<String>,
738    /// The visibility of the label in the label list in the Gmail web interface.
739    #[serde(rename = "labelListVisibility")]
740    pub label_list_visibility: Option<String>,
741    /// The visibility of messages with this label in the message list in the Gmail web interface.
742    #[serde(rename = "messageListVisibility")]
743    pub message_list_visibility: Option<String>,
744    /// The total number of messages with the label.
745    #[serde(rename = "messagesTotal")]
746    pub messages_total: Option<i32>,
747    /// The number of unread messages with the label.
748    #[serde(rename = "messagesUnread")]
749    pub messages_unread: Option<i32>,
750    /// The display name of the label.
751    pub name: Option<String>,
752    /// The total number of threads with the label.
753    #[serde(rename = "threadsTotal")]
754    pub threads_total: Option<i32>,
755    /// The number of unread threads with the label.
756    #[serde(rename = "threadsUnread")]
757    pub threads_unread: Option<i32>,
758    /// The owner type for the label. User labels are created by the user and can be modified and deleted by the user and can be applied to any message or thread. System labels are internally created and cannot be added, modified, or deleted. System labels may be able to be applied to or removed from messages and threads under some circumstances but this is not guaranteed. For example, users can apply and remove the `INBOX` and `UNREAD` labels from messages and threads, but cannot apply or remove the `DRAFTS` or `SENT` labels from messages or threads.
759    #[serde(rename = "type")]
760    pub type_: Option<String>,
761}
762
763impl common::RequestValue for Label {}
764impl common::ResponseResult for Label {}
765
766/// There is no detailed description.
767///
768/// This type is not used in any activity, and only used as *part* of another schema.
769///
770#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
771#[serde_with::serde_as]
772#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
773pub struct LabelColor {
774    /// The background color represented as hex string #RRGGBB (ex #000000). This field is required in order to set the color of a label. Only the following predefined set of color values are allowed: \#000000, #434343, #666666, #999999, #cccccc, #efefef, #f3f3f3, #ffffff, \#fb4c2f, #ffad47, #fad165, #16a766, #43d692, #4a86e8, #a479e2, #f691b3, \#f6c5be, #ffe6c7, #fef1d1, #b9e4d0, #c6f3de, #c9daf8, #e4d7f5, #fcdee8, \#efa093, #ffd6a2, #fce8b3, #89d3b2, #a0eac9, #a4c2f4, #d0bcf1, #fbc8d9, \#e66550, #ffbc6b, #fcda83, #44b984, #68dfa9, #6d9eeb, #b694e8, #f7a7c0, \#cc3a21, #eaa041, #f2c960, #149e60, #3dc789, #3c78d8, #8e63ce, #e07798, \#ac2b16, #cf8933, #d5ae49, #0b804b, #2a9c68, #285bac, #653e9b, #b65775, \#822111, #a46a21, #aa8831, #076239, #1a764d, #1c4587, #41236d, #83334c \#464646, #e7e7e7, #0d3472, #b6cff5, #0d3b44, #98d7e4, #3d188e, #e3d7ff, \#711a36, #fbd3e0, #8a1c0a, #f2b2a8, #7a2e0b, #ffc8af, #7a4706, #ffdeb5, \#594c05, #fbe983, #684e07, #fdedc1, #0b4f30, #b3efd3, #04502e, #a2dcc1, \#c2c2c2, #4986e7, #2da2bb, #b99aff, #994a64, #f691b2, #ff7537, #ffad46, \#662e37, #ebdbde, #cca6ac, #094228, #42d692, #16a765
775    #[serde(rename = "backgroundColor")]
776    pub background_color: Option<String>,
777    /// The text color of the label, represented as hex string. This field is required in order to set the color of a label. Only the following predefined set of color values are allowed: \#000000, #434343, #666666, #999999, #cccccc, #efefef, #f3f3f3, #ffffff, \#fb4c2f, #ffad47, #fad165, #16a766, #43d692, #4a86e8, #a479e2, #f691b3, \#f6c5be, #ffe6c7, #fef1d1, #b9e4d0, #c6f3de, #c9daf8, #e4d7f5, #fcdee8, \#efa093, #ffd6a2, #fce8b3, #89d3b2, #a0eac9, #a4c2f4, #d0bcf1, #fbc8d9, \#e66550, #ffbc6b, #fcda83, #44b984, #68dfa9, #6d9eeb, #b694e8, #f7a7c0, \#cc3a21, #eaa041, #f2c960, #149e60, #3dc789, #3c78d8, #8e63ce, #e07798, \#ac2b16, #cf8933, #d5ae49, #0b804b, #2a9c68, #285bac, #653e9b, #b65775, \#822111, #a46a21, #aa8831, #076239, #1a764d, #1c4587, #41236d, #83334c \#464646, #e7e7e7, #0d3472, #b6cff5, #0d3b44, #98d7e4, #3d188e, #e3d7ff, \#711a36, #fbd3e0, #8a1c0a, #f2b2a8, #7a2e0b, #ffc8af, #7a4706, #ffdeb5, \#594c05, #fbe983, #684e07, #fdedc1, #0b4f30, #b3efd3, #04502e, #a2dcc1, \#c2c2c2, #4986e7, #2da2bb, #b99aff, #994a64, #f691b2, #ff7537, #ffad46, \#662e37, #ebdbde, #cca6ac, #094228, #42d692, #16a765
778    #[serde(rename = "textColor")]
779    pub text_color: Option<String>,
780}
781
782impl common::Part for LabelColor {}
783
784/// Language settings for an account. These settings correspond to the “Language settings” feature in the web interface.
785///
786/// # Activities
787///
788/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
789/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
790///
791/// * [settings get language users](UserSettingGetLanguageCall) (response)
792/// * [settings update language users](UserSettingUpdateLanguageCall) (request|response)
793#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
794#[serde_with::serde_as]
795#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
796pub struct LanguageSettings {
797    /// The language to display Gmail in, formatted as an RFC 3066 Language Tag (for example `en-GB`, `fr` or `ja` for British English, French, or Japanese respectively). The set of languages supported by Gmail evolves over time, so please refer to the "Language" dropdown in the Gmail settings for all available options, as described in the language settings help article. A table of sample values is also provided in the Managing Language Settings guide Not all Gmail clients can display the same set of languages. In the case that a user's display language is not available for use on a particular client, said client automatically chooses to display in the closest supported variant (or a reasonable default).
798    #[serde(rename = "displayLanguage")]
799    pub display_language: Option<String>,
800}
801
802impl common::RequestValue for LanguageSettings {}
803impl common::ResponseResult for LanguageSettings {}
804
805/// There is no detailed description.
806///
807/// # Activities
808///
809/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
810/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
811///
812/// * [settings cse identities list users](UserSettingCseIdentityListCall) (response)
813#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
814#[serde_with::serde_as]
815#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
816pub struct ListCseIdentitiesResponse {
817    /// One page of the list of CSE identities configured for the user.
818    #[serde(rename = "cseIdentities")]
819    pub cse_identities: Option<Vec<CseIdentity>>,
820    /// Pagination token to be passed to a subsequent ListCseIdentities call in order to retrieve the next page of identities. If this value is not returned or is the empty string, then no further pages remain.
821    #[serde(rename = "nextPageToken")]
822    pub next_page_token: Option<String>,
823}
824
825impl common::ResponseResult for ListCseIdentitiesResponse {}
826
827/// There is no detailed description.
828///
829/// # Activities
830///
831/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
832/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
833///
834/// * [settings cse keypairs list users](UserSettingCseKeypairListCall) (response)
835#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
836#[serde_with::serde_as]
837#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
838pub struct ListCseKeyPairsResponse {
839    /// One page of the list of CSE key pairs installed for the user.
840    #[serde(rename = "cseKeyPairs")]
841    pub cse_key_pairs: Option<Vec<CseKeyPair>>,
842    /// Pagination token to be passed to a subsequent ListCseKeyPairs call in order to retrieve the next page of key pairs. If this value is not returned, then no further pages remain.
843    #[serde(rename = "nextPageToken")]
844    pub next_page_token: Option<String>,
845}
846
847impl common::ResponseResult for ListCseKeyPairsResponse {}
848
849/// Response for the ListDelegates method.
850///
851/// # Activities
852///
853/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
854/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
855///
856/// * [settings delegates list users](UserSettingDelegateListCall) (response)
857#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
858#[serde_with::serde_as]
859#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
860pub struct ListDelegatesResponse {
861    /// List of the user's delegates (with any verification status). If an account doesn't have delegates, this field doesn't appear.
862    pub delegates: Option<Vec<Delegate>>,
863}
864
865impl common::ResponseResult for ListDelegatesResponse {}
866
867/// There is no detailed description.
868///
869/// # Activities
870///
871/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
872/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
873///
874/// * [drafts list users](UserDraftListCall) (response)
875#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
876#[serde_with::serde_as]
877#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
878pub struct ListDraftsResponse {
879    /// List of drafts. Note that the `Message` property in each `Draft` resource only contains an `id` and a `threadId`. The messages.get method can fetch additional message details.
880    pub drafts: Option<Vec<Draft>>,
881    /// Token to retrieve the next page of results in the list.
882    #[serde(rename = "nextPageToken")]
883    pub next_page_token: Option<String>,
884    /// Estimated total number of results.
885    #[serde(rename = "resultSizeEstimate")]
886    pub result_size_estimate: Option<u32>,
887}
888
889impl common::ResponseResult for ListDraftsResponse {}
890
891/// Response for the ListFilters method.
892///
893/// # Activities
894///
895/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
896/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
897///
898/// * [settings filters list users](UserSettingFilterListCall) (response)
899#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
900#[serde_with::serde_as]
901#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
902pub struct ListFiltersResponse {
903    /// List of a user's filters.
904    pub filter: Option<Vec<Filter>>,
905}
906
907impl common::ResponseResult for ListFiltersResponse {}
908
909/// Response for the ListForwardingAddresses method.
910///
911/// # Activities
912///
913/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
914/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
915///
916/// * [settings forwarding addresses list users](UserSettingForwardingAddressListCall) (response)
917#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
918#[serde_with::serde_as]
919#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
920pub struct ListForwardingAddressesResponse {
921    /// List of addresses that may be used for forwarding.
922    #[serde(rename = "forwardingAddresses")]
923    pub forwarding_addresses: Option<Vec<ForwardingAddress>>,
924}
925
926impl common::ResponseResult for ListForwardingAddressesResponse {}
927
928/// There is no detailed description.
929///
930/// # Activities
931///
932/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
933/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
934///
935/// * [history list users](UserHistoryListCall) (response)
936#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
937#[serde_with::serde_as]
938#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
939pub struct ListHistoryResponse {
940    /// List of history records. Any `messages` contained in the response will typically only have `id` and `threadId` fields populated.
941    pub history: Option<Vec<History>>,
942    /// The ID of the mailbox's current history record.
943    #[serde(rename = "historyId")]
944    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
945    pub history_id: Option<u64>,
946    /// Page token to retrieve the next page of results in the list.
947    #[serde(rename = "nextPageToken")]
948    pub next_page_token: Option<String>,
949}
950
951impl common::ResponseResult for ListHistoryResponse {}
952
953/// There is no detailed description.
954///
955/// # Activities
956///
957/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
958/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
959///
960/// * [labels list users](UserLabelListCall) (response)
961#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
962#[serde_with::serde_as]
963#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
964pub struct ListLabelsResponse {
965    /// List of labels. Note that each label resource only contains an `id`, `name`, `messageListVisibility`, `labelListVisibility`, and `type`. The labels.get method can fetch additional label details.
966    pub labels: Option<Vec<Label>>,
967}
968
969impl common::ResponseResult for ListLabelsResponse {}
970
971/// There is no detailed description.
972///
973/// # Activities
974///
975/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
976/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
977///
978/// * [messages list users](UserMessageListCall) (response)
979#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
980#[serde_with::serde_as]
981#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
982pub struct ListMessagesResponse {
983    /// List of messages. Note that each message resource contains only an `id` and a `threadId`. Additional message details can be fetched using the messages.get method.
984    pub messages: Option<Vec<Message>>,
985    /// Token to retrieve the next page of results in the list.
986    #[serde(rename = "nextPageToken")]
987    pub next_page_token: Option<String>,
988    /// Estimated total number of results.
989    #[serde(rename = "resultSizeEstimate")]
990    pub result_size_estimate: Option<u32>,
991}
992
993impl common::ResponseResult for ListMessagesResponse {}
994
995/// Response for the ListSendAs method.
996///
997/// # Activities
998///
999/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1000/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1001///
1002/// * [settings send as list users](UserSettingSendAListCall) (response)
1003#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1004#[serde_with::serde_as]
1005#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1006pub struct ListSendAsResponse {
1007    /// List of send-as aliases.
1008    #[serde(rename = "sendAs")]
1009    pub send_as: Option<Vec<SendAs>>,
1010}
1011
1012impl common::ResponseResult for ListSendAsResponse {}
1013
1014/// There is no detailed description.
1015///
1016/// # Activities
1017///
1018/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1019/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1020///
1021/// * [settings send as smime info list users](UserSettingSendASmimeInfoListCall) (response)
1022#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1023#[serde_with::serde_as]
1024#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1025pub struct ListSmimeInfoResponse {
1026    /// List of SmimeInfo.
1027    #[serde(rename = "smimeInfo")]
1028    pub smime_info: Option<Vec<SmimeInfo>>,
1029}
1030
1031impl common::ResponseResult for ListSmimeInfoResponse {}
1032
1033/// There is no detailed description.
1034///
1035/// # Activities
1036///
1037/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1038/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1039///
1040/// * [threads list users](UserThreadListCall) (response)
1041#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1042#[serde_with::serde_as]
1043#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1044pub struct ListThreadsResponse {
1045    /// Page token to retrieve the next page of results in the list.
1046    #[serde(rename = "nextPageToken")]
1047    pub next_page_token: Option<String>,
1048    /// Estimated total number of results.
1049    #[serde(rename = "resultSizeEstimate")]
1050    pub result_size_estimate: Option<u32>,
1051    /// List of threads. Note that each thread resource does not contain a list of `messages`. The list of `messages` for a given thread can be fetched using the threads.get method.
1052    pub threads: Option<Vec<Thread>>,
1053}
1054
1055impl common::ResponseResult for ListThreadsResponse {}
1056
1057/// An email message.
1058///
1059/// # Activities
1060///
1061/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1062/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1063///
1064/// * [drafts send users](UserDraftSendCall) (response)
1065/// * [messages get users](UserMessageGetCall) (response)
1066/// * [messages import users](UserMessageImportCall) (request|response)
1067/// * [messages insert users](UserMessageInsertCall) (request|response)
1068/// * [messages modify users](UserMessageModifyCall) (response)
1069/// * [messages send users](UserMessageSendCall) (request|response)
1070/// * [messages trash users](UserMessageTrashCall) (response)
1071/// * [messages untrash users](UserMessageUntrashCall) (response)
1072#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1073#[serde_with::serde_as]
1074#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1075pub struct Message {
1076    /// The ID of the last history record that modified this message.
1077    #[serde(rename = "historyId")]
1078    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
1079    pub history_id: Option<u64>,
1080    /// The immutable ID of the message.
1081    pub id: Option<String>,
1082    /// The internal message creation timestamp (epoch ms), which determines ordering in the inbox. For normal SMTP-received email, this represents the time the message was originally accepted by Google, which is more reliable than the `Date` header. However, for API-migrated mail, it can be configured by client to be based on the `Date` header.
1083    #[serde(rename = "internalDate")]
1084    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
1085    pub internal_date: Option<i64>,
1086    /// List of IDs of labels applied to this message.
1087    #[serde(rename = "labelIds")]
1088    pub label_ids: Option<Vec<String>>,
1089    /// The parsed email structure in the message parts.
1090    pub payload: Option<MessagePart>,
1091    /// The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in `messages.get` and `drafts.get` responses when the `format=RAW` parameter is supplied.
1092    #[serde_as(as = "Option<common::serde::urlsafe_base64::Wrapper>")]
1093    pub raw: Option<Vec<u8>>,
1094    /// Estimated size in bytes of the message.
1095    #[serde(rename = "sizeEstimate")]
1096    pub size_estimate: Option<i32>,
1097    /// A short part of the message text.
1098    pub snippet: Option<String>,
1099    /// The ID of the thread the message belongs to. To add a message or draft to a thread, the following criteria must be met: 1. The requested `threadId` must be specified on the `Message` or `Draft.Message` you supply with your request. 2. The `References` and `In-Reply-To` headers must be set in compliance with the [RFC 2822](https://tools.ietf.org/html/rfc2822) standard. 3. The `Subject` headers must match.
1100    #[serde(rename = "threadId")]
1101    pub thread_id: Option<String>,
1102}
1103
1104impl common::RequestValue for Message {}
1105impl common::ResponseResult for Message {}
1106
1107/// A single MIME message part.
1108///
1109/// This type is not used in any activity, and only used as *part* of another schema.
1110///
1111#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1112#[serde_with::serde_as]
1113#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1114pub struct MessagePart {
1115    /// The message part body for this part, which may be empty for container MIME message parts.
1116    pub body: Option<MessagePartBody>,
1117    /// The filename of the attachment. Only present if this message part represents an attachment.
1118    pub filename: Option<String>,
1119    /// List of headers on this message part. For the top-level message part, representing the entire message payload, it will contain the standard RFC 2822 email headers such as `To`, `From`, and `Subject`.
1120    pub headers: Option<Vec<MessagePartHeader>>,
1121    /// The MIME type of the message part.
1122    #[serde(rename = "mimeType")]
1123    pub mime_type: Option<String>,
1124    /// The immutable ID of the message part.
1125    #[serde(rename = "partId")]
1126    pub part_id: Option<String>,
1127    /// The child MIME message parts of this part. This only applies to container MIME message parts, for example `multipart/*`. For non- container MIME message part types, such as `text/plain`, this field is empty. For more information, see RFC 1521.
1128    pub parts: Option<Vec<MessagePart>>,
1129}
1130
1131impl common::Part for MessagePart {}
1132
1133/// The body of a single MIME message part.
1134///
1135/// # Activities
1136///
1137/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1138/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1139///
1140/// * [messages attachments get users](UserMessageAttachmentGetCall) (response)
1141#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1142#[serde_with::serde_as]
1143#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1144pub struct MessagePartBody {
1145    /// When present, contains the ID of an external attachment that can be retrieved in a separate `messages.attachments.get` request. When not present, the entire content of the message part body is contained in the data field.
1146    #[serde(rename = "attachmentId")]
1147    pub attachment_id: Option<String>,
1148    /// The body data of a MIME message part as a base64url encoded string. May be empty for MIME container types that have no message body or when the body data is sent as a separate attachment. An attachment ID is present if the body data is contained in a separate attachment.
1149    #[serde_as(as = "Option<common::serde::urlsafe_base64::Wrapper>")]
1150    pub data: Option<Vec<u8>>,
1151    /// Number of bytes for the message part data (encoding notwithstanding).
1152    pub size: Option<i32>,
1153}
1154
1155impl common::ResponseResult for MessagePartBody {}
1156
1157/// There is no detailed description.
1158///
1159/// This type is not used in any activity, and only used as *part* of another schema.
1160///
1161#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1162#[serde_with::serde_as]
1163#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1164pub struct MessagePartHeader {
1165    /// The name of the header before the `:` separator. For example, `To`.
1166    pub name: Option<String>,
1167    /// The value of the header after the `:` separator. For example, `someuser@example.com`.
1168    pub value: Option<String>,
1169}
1170
1171impl common::Part for MessagePartHeader {}
1172
1173/// There is no detailed description.
1174///
1175/// # Activities
1176///
1177/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1178/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1179///
1180/// * [messages modify users](UserMessageModifyCall) (request)
1181#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1182#[serde_with::serde_as]
1183#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1184pub struct ModifyMessageRequest {
1185    /// A list of IDs of labels to add to this message. You can add up to 100 labels with each update.
1186    #[serde(rename = "addLabelIds")]
1187    pub add_label_ids: Option<Vec<String>>,
1188    /// A list IDs of labels to remove from this message. You can remove up to 100 labels with each update.
1189    #[serde(rename = "removeLabelIds")]
1190    pub remove_label_ids: Option<Vec<String>>,
1191}
1192
1193impl common::RequestValue for ModifyMessageRequest {}
1194
1195/// There is no detailed description.
1196///
1197/// # Activities
1198///
1199/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1200/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1201///
1202/// * [threads modify users](UserThreadModifyCall) (request)
1203#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1204#[serde_with::serde_as]
1205#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1206pub struct ModifyThreadRequest {
1207    /// A list of IDs of labels to add to this thread. You can add up to 100 labels with each update.
1208    #[serde(rename = "addLabelIds")]
1209    pub add_label_ids: Option<Vec<String>>,
1210    /// A list of IDs of labels to remove from this thread. You can remove up to 100 labels with each update.
1211    #[serde(rename = "removeLabelIds")]
1212    pub remove_label_ids: Option<Vec<String>>,
1213}
1214
1215impl common::RequestValue for ModifyThreadRequest {}
1216
1217/// Request to obliterate a CSE key pair.
1218///
1219/// # Activities
1220///
1221/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1222/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1223///
1224/// * [settings cse keypairs obliterate users](UserSettingCseKeypairObliterateCall) (request)
1225#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1226#[serde_with::serde_as]
1227#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1228pub struct ObliterateCseKeyPairRequest {
1229    _never_set: Option<bool>,
1230}
1231
1232impl common::RequestValue for ObliterateCseKeyPairRequest {}
1233
1234/// POP settings for an account.
1235///
1236/// # Activities
1237///
1238/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1239/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1240///
1241/// * [settings get pop users](UserSettingGetPopCall) (response)
1242/// * [settings update pop users](UserSettingUpdatePopCall) (request|response)
1243#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1244#[serde_with::serde_as]
1245#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1246pub struct PopSettings {
1247    /// The range of messages which are accessible via POP.
1248    #[serde(rename = "accessWindow")]
1249    pub access_window: Option<String>,
1250    /// The action that will be executed on a message after it has been fetched via POP.
1251    pub disposition: Option<String>,
1252}
1253
1254impl common::RequestValue for PopSettings {}
1255impl common::ResponseResult for PopSettings {}
1256
1257/// Profile for a Gmail user.
1258///
1259/// # Activities
1260///
1261/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1262/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1263///
1264/// * [get profile users](UserGetProfileCall) (response)
1265#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1266#[serde_with::serde_as]
1267#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1268pub struct Profile {
1269    /// The user's email address.
1270    #[serde(rename = "emailAddress")]
1271    pub email_address: Option<String>,
1272    /// The ID of the mailbox's current history record.
1273    #[serde(rename = "historyId")]
1274    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
1275    pub history_id: Option<u64>,
1276    /// The total number of messages in the mailbox.
1277    #[serde(rename = "messagesTotal")]
1278    pub messages_total: Option<i32>,
1279    /// The total number of threads in the mailbox.
1280    #[serde(rename = "threadsTotal")]
1281    pub threads_total: Option<i32>,
1282}
1283
1284impl common::ResponseResult for Profile {}
1285
1286/// Settings associated with a send-as alias, which can be either the primary login address associated with the account or a custom “from” address. Send-as aliases correspond to the “Send Mail As” feature in the web interface.
1287///
1288/// # Activities
1289///
1290/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1291/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1292///
1293/// * [settings send as create users](UserSettingSendACreateCall) (request|response)
1294/// * [settings send as get users](UserSettingSendAGetCall) (response)
1295/// * [settings send as patch users](UserSettingSendAPatchCall) (request|response)
1296/// * [settings send as update users](UserSettingSendAUpdateCall) (request|response)
1297#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1298#[serde_with::serde_as]
1299#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1300pub struct SendAs {
1301    /// A name that appears in the "From:" header for mail sent using this alias. For custom "from" addresses, when this is empty, Gmail will populate the "From:" header with the name that is used for the primary address associated with the account. If the admin has disabled the ability for users to update their name format, requests to update this field for the primary login will silently fail.
1302    #[serde(rename = "displayName")]
1303    pub display_name: Option<String>,
1304    /// Whether this address is selected as the default "From:" address in situations such as composing a new message or sending a vacation auto-reply. Every Gmail account has exactly one default send-as address, so the only legal value that clients may write to this field is `true`. Changing this from `false` to `true` for an address will result in this field becoming `false` for the other previous default address.
1305    #[serde(rename = "isDefault")]
1306    pub is_default: Option<bool>,
1307    /// Whether this address is the primary address used to login to the account. Every Gmail account has exactly one primary address, and it cannot be deleted from the collection of send-as aliases. This field is read-only.
1308    #[serde(rename = "isPrimary")]
1309    pub is_primary: Option<bool>,
1310    /// An optional email address that is included in a "Reply-To:" header for mail sent using this alias. If this is empty, Gmail will not generate a "Reply-To:" header.
1311    #[serde(rename = "replyToAddress")]
1312    pub reply_to_address: Option<String>,
1313    /// The email address that appears in the "From:" header for mail sent using this alias. This is read-only for all operations except create.
1314    #[serde(rename = "sendAsEmail")]
1315    pub send_as_email: Option<String>,
1316    /// An optional HTML signature that is included in messages composed with this alias in the Gmail web UI. This signature is added to new emails only.
1317    pub signature: Option<String>,
1318    /// An optional SMTP service that will be used as an outbound relay for mail sent using this alias. If this is empty, outbound mail will be sent directly from Gmail's servers to the destination SMTP service. This setting only applies to custom "from" aliases.
1319    #[serde(rename = "smtpMsa")]
1320    pub smtp_msa: Option<SmtpMsa>,
1321    /// Whether Gmail should treat this address as an alias for the user's primary email address. This setting only applies to custom "from" aliases.
1322    #[serde(rename = "treatAsAlias")]
1323    pub treat_as_alias: Option<bool>,
1324    /// Indicates whether this address has been verified for use as a send-as alias. Read-only. This setting only applies to custom "from" aliases.
1325    #[serde(rename = "verificationStatus")]
1326    pub verification_status: Option<String>,
1327}
1328
1329impl common::RequestValue for SendAs {}
1330impl common::ResponseResult for SendAs {}
1331
1332/// The configuration of a CSE identity that uses different key pairs for signing and encryption.
1333///
1334/// This type is not used in any activity, and only used as *part* of another schema.
1335///
1336#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1337#[serde_with::serde_as]
1338#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1339pub struct SignAndEncryptKeyPairs {
1340    /// The ID of the CseKeyPair that encrypts signed outgoing mail.
1341    #[serde(rename = "encryptionKeyPairId")]
1342    pub encryption_key_pair_id: Option<String>,
1343    /// The ID of the CseKeyPair that signs outgoing mail.
1344    #[serde(rename = "signingKeyPairId")]
1345    pub signing_key_pair_id: Option<String>,
1346}
1347
1348impl common::Part for SignAndEncryptKeyPairs {}
1349
1350/// An S/MIME email config.
1351///
1352/// # Activities
1353///
1354/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1355/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1356///
1357/// * [settings send as smime info get users](UserSettingSendASmimeInfoGetCall) (response)
1358/// * [settings send as smime info insert users](UserSettingSendASmimeInfoInsertCall) (request|response)
1359#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1360#[serde_with::serde_as]
1361#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1362pub struct SmimeInfo {
1363    /// Encrypted key password, when key is encrypted.
1364    #[serde(rename = "encryptedKeyPassword")]
1365    pub encrypted_key_password: Option<String>,
1366    /// When the certificate expires (in milliseconds since epoch).
1367    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
1368    pub expiration: Option<i64>,
1369    /// The immutable ID for the SmimeInfo.
1370    pub id: Option<String>,
1371    /// Whether this SmimeInfo is the default one for this user's send-as address.
1372    #[serde(rename = "isDefault")]
1373    pub is_default: Option<bool>,
1374    /// The S/MIME certificate issuer's common name.
1375    #[serde(rename = "issuerCn")]
1376    pub issuer_cn: Option<String>,
1377    /// PEM formatted X509 concatenated certificate string (standard base64 encoding). Format used for returning key, which includes public key as well as certificate chain (not private key).
1378    pub pem: Option<String>,
1379    /// PKCS#12 format containing a single private/public key pair and certificate chain. This format is only accepted from client for creating a new SmimeInfo and is never returned, because the private key is not intended to be exported. PKCS#12 may be encrypted, in which case encryptedKeyPassword should be set appropriately.
1380    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
1381    pub pkcs12: Option<Vec<u8>>,
1382}
1383
1384impl common::RequestValue for SmimeInfo {}
1385impl common::ResponseResult for SmimeInfo {}
1386
1387/// Configuration for communication with an SMTP service.
1388///
1389/// This type is not used in any activity, and only used as *part* of another schema.
1390///
1391#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1392#[serde_with::serde_as]
1393#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1394pub struct SmtpMsa {
1395    /// The hostname of the SMTP service. Required.
1396    pub host: Option<String>,
1397    /// The password that will be used for authentication with the SMTP service. This is a write-only field that can be specified in requests to create or update SendAs settings; it is never populated in responses.
1398    pub password: Option<String>,
1399    /// The port of the SMTP service. Required.
1400    pub port: Option<i32>,
1401    /// The protocol that will be used to secure communication with the SMTP service. Required.
1402    #[serde(rename = "securityMode")]
1403    pub security_mode: Option<String>,
1404    /// The username that will be used for authentication with the SMTP service. This is a write-only field that can be specified in requests to create or update SendAs settings; it is never populated in responses.
1405    pub username: Option<String>,
1406}
1407
1408impl common::Part for SmtpMsa {}
1409
1410/// A collection of messages representing a conversation.
1411///
1412/// # Activities
1413///
1414/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1415/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1416///
1417/// * [threads get users](UserThreadGetCall) (response)
1418/// * [threads modify users](UserThreadModifyCall) (response)
1419/// * [threads trash users](UserThreadTrashCall) (response)
1420/// * [threads untrash users](UserThreadUntrashCall) (response)
1421#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1422#[serde_with::serde_as]
1423#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1424pub struct Thread {
1425    /// The ID of the last history record that modified this thread.
1426    #[serde(rename = "historyId")]
1427    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
1428    pub history_id: Option<u64>,
1429    /// The unique ID of the thread.
1430    pub id: Option<String>,
1431    /// The list of messages in the thread.
1432    pub messages: Option<Vec<Message>>,
1433    /// A short part of the message text.
1434    pub snippet: Option<String>,
1435}
1436
1437impl common::ResponseResult for Thread {}
1438
1439/// Vacation auto-reply settings for an account. These settings correspond to the “Vacation responder” feature in the web interface.
1440///
1441/// # Activities
1442///
1443/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1444/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1445///
1446/// * [settings get vacation users](UserSettingGetVacationCall) (response)
1447/// * [settings update vacation users](UserSettingUpdateVacationCall) (request|response)
1448#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1449#[serde_with::serde_as]
1450#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1451pub struct VacationSettings {
1452    /// Flag that controls whether Gmail automatically replies to messages.
1453    #[serde(rename = "enableAutoReply")]
1454    pub enable_auto_reply: Option<bool>,
1455    /// An optional end time for sending auto-replies (epoch ms). When this is specified, Gmail will automatically reply only to messages that it receives before the end time. If both `startTime` and `endTime` are specified, `startTime` must precede `endTime`.
1456    #[serde(rename = "endTime")]
1457    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
1458    pub end_time: Option<i64>,
1459    /// Response body in HTML format. Gmail will sanitize the HTML before storing it. If both `response_body_plain_text` and `response_body_html` are specified, `response_body_html` will be used.
1460    #[serde(rename = "responseBodyHtml")]
1461    pub response_body_html: Option<String>,
1462    /// Response body in plain text format. If both `response_body_plain_text` and `response_body_html` are specified, `response_body_html` will be used.
1463    #[serde(rename = "responseBodyPlainText")]
1464    pub response_body_plain_text: Option<String>,
1465    /// Optional text to prepend to the subject line in vacation responses. In order to enable auto-replies, either the response subject or the response body must be nonempty.
1466    #[serde(rename = "responseSubject")]
1467    pub response_subject: Option<String>,
1468    /// Flag that determines whether responses are sent to recipients who are not in the user's list of contacts.
1469    #[serde(rename = "restrictToContacts")]
1470    pub restrict_to_contacts: Option<bool>,
1471    /// Flag that determines whether responses are sent to recipients who are outside of the user's domain. This feature is only available for Google Workspace users.
1472    #[serde(rename = "restrictToDomain")]
1473    pub restrict_to_domain: Option<bool>,
1474    /// An optional start time for sending auto-replies (epoch ms). When this is specified, Gmail will automatically reply only to messages that it receives after the start time. If both `startTime` and `endTime` are specified, `startTime` must precede `endTime`.
1475    #[serde(rename = "startTime")]
1476    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
1477    pub start_time: Option<i64>,
1478}
1479
1480impl common::RequestValue for VacationSettings {}
1481impl common::ResponseResult for VacationSettings {}
1482
1483/// Set up or update a new push notification watch on this user’s mailbox.
1484///
1485/// # Activities
1486///
1487/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1488/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1489///
1490/// * [watch users](UserWatchCall) (request)
1491#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1492#[serde_with::serde_as]
1493#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1494pub struct WatchRequest {
1495    /// Filtering behavior of `labelIds list` specified. This field is deprecated because it caused incorrect behavior in some cases; use `label_filter_behavior` instead.
1496    #[serde(rename = "labelFilterAction")]
1497    pub label_filter_action: Option<String>,
1498    /// Filtering behavior of `labelIds list` specified. This field replaces `label_filter_action`; if set, `label_filter_action` is ignored.
1499    #[serde(rename = "labelFilterBehavior")]
1500    pub label_filter_behavior: Option<String>,
1501    /// List of label_ids to restrict notifications about. By default, if unspecified, all changes are pushed out. If specified then dictates which labels are required for a push notification to be generated.
1502    #[serde(rename = "labelIds")]
1503    pub label_ids: Option<Vec<String>>,
1504    /// A fully qualified Google Cloud Pub/Sub API topic name to publish the events to. This topic name **must** already exist in Cloud Pub/Sub and you **must** have already granted gmail "publish" permission on it. For example, "projects/my-project-identifier/topics/my-topic-name" (using the Cloud Pub/Sub "v1" topic naming format). Note that the "my-project-identifier" portion must exactly match your Google developer project id (the one executing this watch request).
1505    #[serde(rename = "topicName")]
1506    pub topic_name: Option<String>,
1507}
1508
1509impl common::RequestValue for WatchRequest {}
1510
1511/// Push notification watch response.
1512///
1513/// # Activities
1514///
1515/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1516/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1517///
1518/// * [watch users](UserWatchCall) (response)
1519#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1520#[serde_with::serde_as]
1521#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1522pub struct WatchResponse {
1523    /// When Gmail will stop sending notifications for mailbox updates (epoch millis). Call `watch` again before this time to renew the watch.
1524    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
1525    pub expiration: Option<i64>,
1526    /// The ID of the mailbox's current history record.
1527    #[serde(rename = "historyId")]
1528    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
1529    pub history_id: Option<u64>,
1530}
1531
1532impl common::ResponseResult for WatchResponse {}
1533
1534// ###################
1535// MethodBuilders ###
1536// #################
1537
1538/// A builder providing access to all methods supported on *user* resources.
1539/// It is not used directly, but through the [`Gmail`] hub.
1540///
1541/// # Example
1542///
1543/// Instantiate a resource builder
1544///
1545/// ```test_harness,no_run
1546/// extern crate hyper;
1547/// extern crate hyper_rustls;
1548/// extern crate google_gmail1 as gmail1;
1549///
1550/// # async fn dox() {
1551/// use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1552///
1553/// let secret: yup_oauth2::ApplicationSecret = Default::default();
1554/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1555///     secret,
1556///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1557/// ).build().await.unwrap();
1558///
1559/// let client = hyper_util::client::legacy::Client::builder(
1560///     hyper_util::rt::TokioExecutor::new()
1561/// )
1562/// .build(
1563///     hyper_rustls::HttpsConnectorBuilder::new()
1564///         .with_native_roots()
1565///         .unwrap()
1566///         .https_or_http()
1567///         .enable_http1()
1568///         .build()
1569/// );
1570/// let mut hub = Gmail::new(client, auth);
1571/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
1572/// // like `drafts_create(...)`, `drafts_delete(...)`, `drafts_get(...)`, `drafts_list(...)`, `drafts_send(...)`, `drafts_update(...)`, `get_profile(...)`, `history_list(...)`, `labels_create(...)`, `labels_delete(...)`, `labels_get(...)`, `labels_list(...)`, `labels_patch(...)`, `labels_update(...)`, `messages_attachments_get(...)`, `messages_batch_delete(...)`, `messages_batch_modify(...)`, `messages_delete(...)`, `messages_get(...)`, `messages_import(...)`, `messages_insert(...)`, `messages_list(...)`, `messages_modify(...)`, `messages_send(...)`, `messages_trash(...)`, `messages_untrash(...)`, `settings_cse_identities_create(...)`, `settings_cse_identities_delete(...)`, `settings_cse_identities_get(...)`, `settings_cse_identities_list(...)`, `settings_cse_identities_patch(...)`, `settings_cse_keypairs_create(...)`, `settings_cse_keypairs_disable(...)`, `settings_cse_keypairs_enable(...)`, `settings_cse_keypairs_get(...)`, `settings_cse_keypairs_list(...)`, `settings_cse_keypairs_obliterate(...)`, `settings_delegates_create(...)`, `settings_delegates_delete(...)`, `settings_delegates_get(...)`, `settings_delegates_list(...)`, `settings_filters_create(...)`, `settings_filters_delete(...)`, `settings_filters_get(...)`, `settings_filters_list(...)`, `settings_forwarding_addresses_create(...)`, `settings_forwarding_addresses_delete(...)`, `settings_forwarding_addresses_get(...)`, `settings_forwarding_addresses_list(...)`, `settings_get_auto_forwarding(...)`, `settings_get_imap(...)`, `settings_get_language(...)`, `settings_get_pop(...)`, `settings_get_vacation(...)`, `settings_send_as_create(...)`, `settings_send_as_delete(...)`, `settings_send_as_get(...)`, `settings_send_as_list(...)`, `settings_send_as_patch(...)`, `settings_send_as_smime_info_delete(...)`, `settings_send_as_smime_info_get(...)`, `settings_send_as_smime_info_insert(...)`, `settings_send_as_smime_info_list(...)`, `settings_send_as_smime_info_set_default(...)`, `settings_send_as_update(...)`, `settings_send_as_verify(...)`, `settings_update_auto_forwarding(...)`, `settings_update_imap(...)`, `settings_update_language(...)`, `settings_update_pop(...)`, `settings_update_vacation(...)`, `stop(...)`, `threads_delete(...)`, `threads_get(...)`, `threads_list(...)`, `threads_modify(...)`, `threads_trash(...)`, `threads_untrash(...)` and `watch(...)`
1573/// // to build up your call.
1574/// let rb = hub.users();
1575/// # }
1576/// ```
1577pub struct UserMethods<'a, C>
1578where
1579    C: 'a,
1580{
1581    hub: &'a Gmail<C>,
1582}
1583
1584impl<'a, C> common::MethodsBuilder for UserMethods<'a, C> {}
1585
1586impl<'a, C> UserMethods<'a, C> {
1587    /// Create a builder to help you perform the following task:
1588    ///
1589    /// Creates a new draft with the `DRAFT` label.
1590    ///
1591    /// # Arguments
1592    ///
1593    /// * `request` - No description provided.
1594    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1595    pub fn drafts_create(&self, request: Draft, user_id: &str) -> UserDraftCreateCall<'a, C> {
1596        UserDraftCreateCall {
1597            hub: self.hub,
1598            _request: request,
1599            _user_id: user_id.to_string(),
1600            _delegate: Default::default(),
1601            _additional_params: Default::default(),
1602            _scopes: Default::default(),
1603        }
1604    }
1605
1606    /// Create a builder to help you perform the following task:
1607    ///
1608    /// Immediately and permanently deletes the specified draft. Does not simply trash it.
1609    ///
1610    /// # Arguments
1611    ///
1612    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1613    /// * `id` - The ID of the draft to delete.
1614    pub fn drafts_delete(&self, user_id: &str, id: &str) -> UserDraftDeleteCall<'a, C> {
1615        UserDraftDeleteCall {
1616            hub: self.hub,
1617            _user_id: user_id.to_string(),
1618            _id: id.to_string(),
1619            _delegate: Default::default(),
1620            _additional_params: Default::default(),
1621            _scopes: Default::default(),
1622        }
1623    }
1624
1625    /// Create a builder to help you perform the following task:
1626    ///
1627    /// Gets the specified draft.
1628    ///
1629    /// # Arguments
1630    ///
1631    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1632    /// * `id` - The ID of the draft to retrieve.
1633    pub fn drafts_get(&self, user_id: &str, id: &str) -> UserDraftGetCall<'a, C> {
1634        UserDraftGetCall {
1635            hub: self.hub,
1636            _user_id: user_id.to_string(),
1637            _id: id.to_string(),
1638            _format: Default::default(),
1639            _delegate: Default::default(),
1640            _additional_params: Default::default(),
1641            _scopes: Default::default(),
1642        }
1643    }
1644
1645    /// Create a builder to help you perform the following task:
1646    ///
1647    /// Lists the drafts in the user's mailbox.
1648    ///
1649    /// # Arguments
1650    ///
1651    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1652    pub fn drafts_list(&self, user_id: &str) -> UserDraftListCall<'a, C> {
1653        UserDraftListCall {
1654            hub: self.hub,
1655            _user_id: user_id.to_string(),
1656            _q: Default::default(),
1657            _page_token: Default::default(),
1658            _max_results: Default::default(),
1659            _include_spam_trash: Default::default(),
1660            _delegate: Default::default(),
1661            _additional_params: Default::default(),
1662            _scopes: Default::default(),
1663        }
1664    }
1665
1666    /// Create a builder to help you perform the following task:
1667    ///
1668    /// Sends the specified, existing draft to the recipients in the `To`, `Cc`, and `Bcc` headers.
1669    ///
1670    /// # Arguments
1671    ///
1672    /// * `request` - No description provided.
1673    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1674    pub fn drafts_send(&self, request: Draft, user_id: &str) -> UserDraftSendCall<'a, C> {
1675        UserDraftSendCall {
1676            hub: self.hub,
1677            _request: request,
1678            _user_id: user_id.to_string(),
1679            _delegate: Default::default(),
1680            _additional_params: Default::default(),
1681            _scopes: Default::default(),
1682        }
1683    }
1684
1685    /// Create a builder to help you perform the following task:
1686    ///
1687    /// Replaces a draft's content.
1688    ///
1689    /// # Arguments
1690    ///
1691    /// * `request` - No description provided.
1692    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1693    /// * `id` - The ID of the draft to update.
1694    pub fn drafts_update(
1695        &self,
1696        request: Draft,
1697        user_id: &str,
1698        id: &str,
1699    ) -> UserDraftUpdateCall<'a, C> {
1700        UserDraftUpdateCall {
1701            hub: self.hub,
1702            _request: request,
1703            _user_id: user_id.to_string(),
1704            _id: id.to_string(),
1705            _delegate: Default::default(),
1706            _additional_params: Default::default(),
1707            _scopes: Default::default(),
1708        }
1709    }
1710
1711    /// Create a builder to help you perform the following task:
1712    ///
1713    /// Lists the history of all changes to the given mailbox. History results are returned in chronological order (increasing `historyId`).
1714    ///
1715    /// # Arguments
1716    ///
1717    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1718    pub fn history_list(&self, user_id: &str) -> UserHistoryListCall<'a, C> {
1719        UserHistoryListCall {
1720            hub: self.hub,
1721            _user_id: user_id.to_string(),
1722            _start_history_id: Default::default(),
1723            _page_token: Default::default(),
1724            _max_results: Default::default(),
1725            _label_id: Default::default(),
1726            _history_types: Default::default(),
1727            _delegate: Default::default(),
1728            _additional_params: Default::default(),
1729            _scopes: Default::default(),
1730        }
1731    }
1732
1733    /// Create a builder to help you perform the following task:
1734    ///
1735    /// Creates a new label.
1736    ///
1737    /// # Arguments
1738    ///
1739    /// * `request` - No description provided.
1740    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1741    pub fn labels_create(&self, request: Label, user_id: &str) -> UserLabelCreateCall<'a, C> {
1742        UserLabelCreateCall {
1743            hub: self.hub,
1744            _request: request,
1745            _user_id: user_id.to_string(),
1746            _delegate: Default::default(),
1747            _additional_params: Default::default(),
1748            _scopes: Default::default(),
1749        }
1750    }
1751
1752    /// Create a builder to help you perform the following task:
1753    ///
1754    /// Immediately and permanently deletes the specified label and removes it from any messages and threads that it is applied to.
1755    ///
1756    /// # Arguments
1757    ///
1758    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1759    /// * `id` - The ID of the label to delete.
1760    pub fn labels_delete(&self, user_id: &str, id: &str) -> UserLabelDeleteCall<'a, C> {
1761        UserLabelDeleteCall {
1762            hub: self.hub,
1763            _user_id: user_id.to_string(),
1764            _id: id.to_string(),
1765            _delegate: Default::default(),
1766            _additional_params: Default::default(),
1767            _scopes: Default::default(),
1768        }
1769    }
1770
1771    /// Create a builder to help you perform the following task:
1772    ///
1773    /// Gets the specified label.
1774    ///
1775    /// # Arguments
1776    ///
1777    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1778    /// * `id` - The ID of the label to retrieve.
1779    pub fn labels_get(&self, user_id: &str, id: &str) -> UserLabelGetCall<'a, C> {
1780        UserLabelGetCall {
1781            hub: self.hub,
1782            _user_id: user_id.to_string(),
1783            _id: id.to_string(),
1784            _delegate: Default::default(),
1785            _additional_params: Default::default(),
1786            _scopes: Default::default(),
1787        }
1788    }
1789
1790    /// Create a builder to help you perform the following task:
1791    ///
1792    /// Lists all labels in the user's mailbox.
1793    ///
1794    /// # Arguments
1795    ///
1796    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1797    pub fn labels_list(&self, user_id: &str) -> UserLabelListCall<'a, C> {
1798        UserLabelListCall {
1799            hub: self.hub,
1800            _user_id: user_id.to_string(),
1801            _delegate: Default::default(),
1802            _additional_params: Default::default(),
1803            _scopes: Default::default(),
1804        }
1805    }
1806
1807    /// Create a builder to help you perform the following task:
1808    ///
1809    /// Patch the specified label.
1810    ///
1811    /// # Arguments
1812    ///
1813    /// * `request` - No description provided.
1814    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1815    /// * `id` - The ID of the label to update.
1816    pub fn labels_patch(
1817        &self,
1818        request: Label,
1819        user_id: &str,
1820        id: &str,
1821    ) -> UserLabelPatchCall<'a, C> {
1822        UserLabelPatchCall {
1823            hub: self.hub,
1824            _request: request,
1825            _user_id: user_id.to_string(),
1826            _id: id.to_string(),
1827            _delegate: Default::default(),
1828            _additional_params: Default::default(),
1829            _scopes: Default::default(),
1830        }
1831    }
1832
1833    /// Create a builder to help you perform the following task:
1834    ///
1835    /// Updates the specified label.
1836    ///
1837    /// # Arguments
1838    ///
1839    /// * `request` - No description provided.
1840    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1841    /// * `id` - The ID of the label to update.
1842    pub fn labels_update(
1843        &self,
1844        request: Label,
1845        user_id: &str,
1846        id: &str,
1847    ) -> UserLabelUpdateCall<'a, C> {
1848        UserLabelUpdateCall {
1849            hub: self.hub,
1850            _request: request,
1851            _user_id: user_id.to_string(),
1852            _id: id.to_string(),
1853            _delegate: Default::default(),
1854            _additional_params: Default::default(),
1855            _scopes: Default::default(),
1856        }
1857    }
1858
1859    /// Create a builder to help you perform the following task:
1860    ///
1861    /// Gets the specified message attachment.
1862    ///
1863    /// # Arguments
1864    ///
1865    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1866    /// * `messageId` - The ID of the message containing the attachment.
1867    /// * `id` - The ID of the attachment.
1868    pub fn messages_attachments_get(
1869        &self,
1870        user_id: &str,
1871        message_id: &str,
1872        id: &str,
1873    ) -> UserMessageAttachmentGetCall<'a, C> {
1874        UserMessageAttachmentGetCall {
1875            hub: self.hub,
1876            _user_id: user_id.to_string(),
1877            _message_id: message_id.to_string(),
1878            _id: id.to_string(),
1879            _delegate: Default::default(),
1880            _additional_params: Default::default(),
1881            _scopes: Default::default(),
1882        }
1883    }
1884
1885    /// Create a builder to help you perform the following task:
1886    ///
1887    /// Deletes many messages by message ID. Provides no guarantees that messages were not already deleted or even existed at all.
1888    ///
1889    /// # Arguments
1890    ///
1891    /// * `request` - No description provided.
1892    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1893    pub fn messages_batch_delete(
1894        &self,
1895        request: BatchDeleteMessagesRequest,
1896        user_id: &str,
1897    ) -> UserMessageBatchDeleteCall<'a, C> {
1898        UserMessageBatchDeleteCall {
1899            hub: self.hub,
1900            _request: request,
1901            _user_id: user_id.to_string(),
1902            _delegate: Default::default(),
1903            _additional_params: Default::default(),
1904            _scopes: Default::default(),
1905        }
1906    }
1907
1908    /// Create a builder to help you perform the following task:
1909    ///
1910    /// Modifies the labels on the specified messages.
1911    ///
1912    /// # Arguments
1913    ///
1914    /// * `request` - No description provided.
1915    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1916    pub fn messages_batch_modify(
1917        &self,
1918        request: BatchModifyMessagesRequest,
1919        user_id: &str,
1920    ) -> UserMessageBatchModifyCall<'a, C> {
1921        UserMessageBatchModifyCall {
1922            hub: self.hub,
1923            _request: request,
1924            _user_id: user_id.to_string(),
1925            _delegate: Default::default(),
1926            _additional_params: Default::default(),
1927            _scopes: Default::default(),
1928        }
1929    }
1930
1931    /// Create a builder to help you perform the following task:
1932    ///
1933    /// Immediately and permanently deletes the specified message. This operation cannot be undone. Prefer `messages.trash` instead.
1934    ///
1935    /// # Arguments
1936    ///
1937    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1938    /// * `id` - The ID of the message to delete.
1939    pub fn messages_delete(&self, user_id: &str, id: &str) -> UserMessageDeleteCall<'a, C> {
1940        UserMessageDeleteCall {
1941            hub: self.hub,
1942            _user_id: user_id.to_string(),
1943            _id: id.to_string(),
1944            _delegate: Default::default(),
1945            _additional_params: Default::default(),
1946            _scopes: Default::default(),
1947        }
1948    }
1949
1950    /// Create a builder to help you perform the following task:
1951    ///
1952    /// Gets the specified message.
1953    ///
1954    /// # Arguments
1955    ///
1956    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1957    /// * `id` - The ID of the message to retrieve. This ID is usually retrieved using `messages.list`. The ID is also contained in the result when a message is inserted (`messages.insert`) or imported (`messages.import`).
1958    pub fn messages_get(&self, user_id: &str, id: &str) -> UserMessageGetCall<'a, C> {
1959        UserMessageGetCall {
1960            hub: self.hub,
1961            _user_id: user_id.to_string(),
1962            _id: id.to_string(),
1963            _metadata_headers: Default::default(),
1964            _format: Default::default(),
1965            _delegate: Default::default(),
1966            _additional_params: Default::default(),
1967            _scopes: Default::default(),
1968        }
1969    }
1970
1971    /// Create a builder to help you perform the following task:
1972    ///
1973    /// Imports a message into only this user's mailbox, with standard email delivery scanning and classification similar to receiving via SMTP. This method doesn't perform SPF checks, so it might not work for some spam messages, such as those attempting to perform domain spoofing. This method does not send a message.
1974    ///
1975    /// # Arguments
1976    ///
1977    /// * `request` - No description provided.
1978    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
1979    pub fn messages_import(&self, request: Message, user_id: &str) -> UserMessageImportCall<'a, C> {
1980        UserMessageImportCall {
1981            hub: self.hub,
1982            _request: request,
1983            _user_id: user_id.to_string(),
1984            _process_for_calendar: Default::default(),
1985            _never_mark_spam: Default::default(),
1986            _internal_date_source: Default::default(),
1987            _deleted: Default::default(),
1988            _delegate: Default::default(),
1989            _additional_params: Default::default(),
1990            _scopes: Default::default(),
1991        }
1992    }
1993
1994    /// Create a builder to help you perform the following task:
1995    ///
1996    /// Directly inserts a message into only this user's mailbox similar to `IMAP APPEND`, bypassing most scanning and classification. Does not send a message.
1997    ///
1998    /// # Arguments
1999    ///
2000    /// * `request` - No description provided.
2001    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
2002    pub fn messages_insert(&self, request: Message, user_id: &str) -> UserMessageInsertCall<'a, C> {
2003        UserMessageInsertCall {
2004            hub: self.hub,
2005            _request: request,
2006            _user_id: user_id.to_string(),
2007            _internal_date_source: Default::default(),
2008            _deleted: Default::default(),
2009            _delegate: Default::default(),
2010            _additional_params: Default::default(),
2011            _scopes: Default::default(),
2012        }
2013    }
2014
2015    /// Create a builder to help you perform the following task:
2016    ///
2017    /// Lists the messages in the user's mailbox.
2018    ///
2019    /// # Arguments
2020    ///
2021    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
2022    pub fn messages_list(&self, user_id: &str) -> UserMessageListCall<'a, C> {
2023        UserMessageListCall {
2024            hub: self.hub,
2025            _user_id: user_id.to_string(),
2026            _q: Default::default(),
2027            _page_token: Default::default(),
2028            _max_results: Default::default(),
2029            _label_ids: Default::default(),
2030            _include_spam_trash: Default::default(),
2031            _delegate: Default::default(),
2032            _additional_params: Default::default(),
2033            _scopes: Default::default(),
2034        }
2035    }
2036
2037    /// Create a builder to help you perform the following task:
2038    ///
2039    /// Modifies the labels on the specified message.
2040    ///
2041    /// # Arguments
2042    ///
2043    /// * `request` - No description provided.
2044    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
2045    /// * `id` - The ID of the message to modify.
2046    pub fn messages_modify(
2047        &self,
2048        request: ModifyMessageRequest,
2049        user_id: &str,
2050        id: &str,
2051    ) -> UserMessageModifyCall<'a, C> {
2052        UserMessageModifyCall {
2053            hub: self.hub,
2054            _request: request,
2055            _user_id: user_id.to_string(),
2056            _id: id.to_string(),
2057            _delegate: Default::default(),
2058            _additional_params: Default::default(),
2059            _scopes: Default::default(),
2060        }
2061    }
2062
2063    /// Create a builder to help you perform the following task:
2064    ///
2065    /// Sends the specified message to the recipients in the `To`, `Cc`, and `Bcc` headers. For example usage, see [Sending email](https://developers.google.com/gmail/api/guides/sending).
2066    ///
2067    /// # Arguments
2068    ///
2069    /// * `request` - No description provided.
2070    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
2071    pub fn messages_send(&self, request: Message, user_id: &str) -> UserMessageSendCall<'a, C> {
2072        UserMessageSendCall {
2073            hub: self.hub,
2074            _request: request,
2075            _user_id: user_id.to_string(),
2076            _delegate: Default::default(),
2077            _additional_params: Default::default(),
2078            _scopes: Default::default(),
2079        }
2080    }
2081
2082    /// Create a builder to help you perform the following task:
2083    ///
2084    /// Moves the specified message to the trash.
2085    ///
2086    /// # Arguments
2087    ///
2088    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
2089    /// * `id` - The ID of the message to Trash.
2090    pub fn messages_trash(&self, user_id: &str, id: &str) -> UserMessageTrashCall<'a, C> {
2091        UserMessageTrashCall {
2092            hub: self.hub,
2093            _user_id: user_id.to_string(),
2094            _id: id.to_string(),
2095            _delegate: Default::default(),
2096            _additional_params: Default::default(),
2097            _scopes: Default::default(),
2098        }
2099    }
2100
2101    /// Create a builder to help you perform the following task:
2102    ///
2103    /// Removes the specified message from the trash.
2104    ///
2105    /// # Arguments
2106    ///
2107    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
2108    /// * `id` - The ID of the message to remove from Trash.
2109    pub fn messages_untrash(&self, user_id: &str, id: &str) -> UserMessageUntrashCall<'a, C> {
2110        UserMessageUntrashCall {
2111            hub: self.hub,
2112            _user_id: user_id.to_string(),
2113            _id: id.to_string(),
2114            _delegate: Default::default(),
2115            _additional_params: Default::default(),
2116            _scopes: Default::default(),
2117        }
2118    }
2119
2120    /// Create a builder to help you perform the following task:
2121    ///
2122    /// Creates and configures a client-side encryption identity that's authorized to send mail from the user account. Google publishes the S/MIME certificate to a shared domain-wide directory so that people within a Google Workspace organization can encrypt and send mail to the identity.
2123    ///
2124    /// # Arguments
2125    ///
2126    /// * `request` - No description provided.
2127    /// * `userId` - The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
2128    pub fn settings_cse_identities_create(
2129        &self,
2130        request: CseIdentity,
2131        user_id: &str,
2132    ) -> UserSettingCseIdentityCreateCall<'a, C> {
2133        UserSettingCseIdentityCreateCall {
2134            hub: self.hub,
2135            _request: request,
2136            _user_id: user_id.to_string(),
2137            _delegate: Default::default(),
2138            _additional_params: Default::default(),
2139            _scopes: Default::default(),
2140        }
2141    }
2142
2143    /// Create a builder to help you perform the following task:
2144    ///
2145    /// Deletes a client-side encryption identity. The authenticated user can no longer use the identity to send encrypted messages. You cannot restore the identity after you delete it. Instead, use the CreateCseIdentity method to create another identity with the same configuration.
2146    ///
2147    /// # Arguments
2148    ///
2149    /// * `userId` - The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
2150    /// * `cseEmailAddress` - The primary email address associated with the client-side encryption identity configuration that's removed.
2151    pub fn settings_cse_identities_delete(
2152        &self,
2153        user_id: &str,
2154        cse_email_address: &str,
2155    ) -> UserSettingCseIdentityDeleteCall<'a, C> {
2156        UserSettingCseIdentityDeleteCall {
2157            hub: self.hub,
2158            _user_id: user_id.to_string(),
2159            _cse_email_address: cse_email_address.to_string(),
2160            _delegate: Default::default(),
2161            _additional_params: Default::default(),
2162            _scopes: Default::default(),
2163        }
2164    }
2165
2166    /// Create a builder to help you perform the following task:
2167    ///
2168    /// Retrieves a client-side encryption identity configuration.
2169    ///
2170    /// # Arguments
2171    ///
2172    /// * `userId` - The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
2173    /// * `cseEmailAddress` - The primary email address associated with the client-side encryption identity configuration that's retrieved.
2174    pub fn settings_cse_identities_get(
2175        &self,
2176        user_id: &str,
2177        cse_email_address: &str,
2178    ) -> UserSettingCseIdentityGetCall<'a, C> {
2179        UserSettingCseIdentityGetCall {
2180            hub: self.hub,
2181            _user_id: user_id.to_string(),
2182            _cse_email_address: cse_email_address.to_string(),
2183            _delegate: Default::default(),
2184            _additional_params: Default::default(),
2185            _scopes: Default::default(),
2186        }
2187    }
2188
2189    /// Create a builder to help you perform the following task:
2190    ///
2191    /// Lists the client-side encrypted identities for an authenticated user.
2192    ///
2193    /// # Arguments
2194    ///
2195    /// * `userId` - The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
2196    pub fn settings_cse_identities_list(
2197        &self,
2198        user_id: &str,
2199    ) -> UserSettingCseIdentityListCall<'a, C> {
2200        UserSettingCseIdentityListCall {
2201            hub: self.hub,
2202            _user_id: user_id.to_string(),
2203            _page_token: Default::default(),
2204            _page_size: Default::default(),
2205            _delegate: Default::default(),
2206            _additional_params: Default::default(),
2207            _scopes: Default::default(),
2208        }
2209    }
2210
2211    /// Create a builder to help you perform the following task:
2212    ///
2213    /// Associates a different key pair with an existing client-side encryption identity. The updated key pair must validate against Google's [S/MIME certificate profiles](https://support.google.com/a/answer/7300887).
2214    ///
2215    /// # Arguments
2216    ///
2217    /// * `request` - No description provided.
2218    /// * `userId` - The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
2219    /// * `emailAddress` - The email address of the client-side encryption identity to update.
2220    pub fn settings_cse_identities_patch(
2221        &self,
2222        request: CseIdentity,
2223        user_id: &str,
2224        email_address: &str,
2225    ) -> UserSettingCseIdentityPatchCall<'a, C> {
2226        UserSettingCseIdentityPatchCall {
2227            hub: self.hub,
2228            _request: request,
2229            _user_id: user_id.to_string(),
2230            _email_address: email_address.to_string(),
2231            _delegate: Default::default(),
2232            _additional_params: Default::default(),
2233            _scopes: Default::default(),
2234        }
2235    }
2236
2237    /// Create a builder to help you perform the following task:
2238    ///
2239    /// Creates and uploads a client-side encryption S/MIME public key certificate chain and private key metadata for the authenticated user.
2240    ///
2241    /// # Arguments
2242    ///
2243    /// * `request` - No description provided.
2244    /// * `userId` - The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
2245    pub fn settings_cse_keypairs_create(
2246        &self,
2247        request: CseKeyPair,
2248        user_id: &str,
2249    ) -> UserSettingCseKeypairCreateCall<'a, C> {
2250        UserSettingCseKeypairCreateCall {
2251            hub: self.hub,
2252            _request: request,
2253            _user_id: user_id.to_string(),
2254            _delegate: Default::default(),
2255            _additional_params: Default::default(),
2256            _scopes: Default::default(),
2257        }
2258    }
2259
2260    /// Create a builder to help you perform the following task:
2261    ///
2262    /// Turns off a client-side encryption key pair. The authenticated user can no longer use the key pair to decrypt incoming CSE message texts or sign outgoing CSE mail. To regain access, use the EnableCseKeyPair to turn on the key pair. After 30 days, you can permanently delete the key pair by using the ObliterateCseKeyPair method.
2263    ///
2264    /// # Arguments
2265    ///
2266    /// * `request` - No description provided.
2267    /// * `userId` - The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
2268    /// * `keyPairId` - The identifier of the key pair to turn off.
2269    pub fn settings_cse_keypairs_disable(
2270        &self,
2271        request: DisableCseKeyPairRequest,
2272        user_id: &str,
2273        key_pair_id: &str,
2274    ) -> UserSettingCseKeypairDisableCall<'a, C> {
2275        UserSettingCseKeypairDisableCall {
2276            hub: self.hub,
2277            _request: request,
2278            _user_id: user_id.to_string(),
2279            _key_pair_id: key_pair_id.to_string(),
2280            _delegate: Default::default(),
2281            _additional_params: Default::default(),
2282            _scopes: Default::default(),
2283        }
2284    }
2285
2286    /// Create a builder to help you perform the following task:
2287    ///
2288    /// Turns on a client-side encryption key pair that was turned off. The key pair becomes active again for any associated client-side encryption identities.
2289    ///
2290    /// # Arguments
2291    ///
2292    /// * `request` - No description provided.
2293    /// * `userId` - The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
2294    /// * `keyPairId` - The identifier of the key pair to turn on.
2295    pub fn settings_cse_keypairs_enable(
2296        &self,
2297        request: EnableCseKeyPairRequest,
2298        user_id: &str,
2299        key_pair_id: &str,
2300    ) -> UserSettingCseKeypairEnableCall<'a, C> {
2301        UserSettingCseKeypairEnableCall {
2302            hub: self.hub,
2303            _request: request,
2304            _user_id: user_id.to_string(),
2305            _key_pair_id: key_pair_id.to_string(),
2306            _delegate: Default::default(),
2307            _additional_params: Default::default(),
2308            _scopes: Default::default(),
2309        }
2310    }
2311
2312    /// Create a builder to help you perform the following task:
2313    ///
2314    /// Retrieves an existing client-side encryption key pair.
2315    ///
2316    /// # Arguments
2317    ///
2318    /// * `userId` - The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
2319    /// * `keyPairId` - The identifier of the key pair to retrieve.
2320    pub fn settings_cse_keypairs_get(
2321        &self,
2322        user_id: &str,
2323        key_pair_id: &str,
2324    ) -> UserSettingCseKeypairGetCall<'a, C> {
2325        UserSettingCseKeypairGetCall {
2326            hub: self.hub,
2327            _user_id: user_id.to_string(),
2328            _key_pair_id: key_pair_id.to_string(),
2329            _delegate: Default::default(),
2330            _additional_params: Default::default(),
2331            _scopes: Default::default(),
2332        }
2333    }
2334
2335    /// Create a builder to help you perform the following task:
2336    ///
2337    /// Lists client-side encryption key pairs for an authenticated user.
2338    ///
2339    /// # Arguments
2340    ///
2341    /// * `userId` - The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
2342    pub fn settings_cse_keypairs_list(
2343        &self,
2344        user_id: &str,
2345    ) -> UserSettingCseKeypairListCall<'a, C> {
2346        UserSettingCseKeypairListCall {
2347            hub: self.hub,
2348            _user_id: user_id.to_string(),
2349            _page_token: Default::default(),
2350            _page_size: Default::default(),
2351            _delegate: Default::default(),
2352            _additional_params: Default::default(),
2353            _scopes: Default::default(),
2354        }
2355    }
2356
2357    /// Create a builder to help you perform the following task:
2358    ///
2359    /// Deletes a client-side encryption key pair permanently and immediately. You can only permanently delete key pairs that have been turned off for more than 30 days. To turn off a key pair, use the DisableCseKeyPair method. Gmail can't restore or decrypt any messages that were encrypted by an obliterated key. Authenticated users and Google Workspace administrators lose access to reading the encrypted messages.
2360    ///
2361    /// # Arguments
2362    ///
2363    /// * `request` - No description provided.
2364    /// * `userId` - The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
2365    /// * `keyPairId` - The identifier of the key pair to obliterate.
2366    pub fn settings_cse_keypairs_obliterate(
2367        &self,
2368        request: ObliterateCseKeyPairRequest,
2369        user_id: &str,
2370        key_pair_id: &str,
2371    ) -> UserSettingCseKeypairObliterateCall<'a, C> {
2372        UserSettingCseKeypairObliterateCall {
2373            hub: self.hub,
2374            _request: request,
2375            _user_id: user_id.to_string(),
2376            _key_pair_id: key_pair_id.to_string(),
2377            _delegate: Default::default(),
2378            _additional_params: Default::default(),
2379            _scopes: Default::default(),
2380        }
2381    }
2382
2383    /// Create a builder to help you perform the following task:
2384    ///
2385    /// Adds a delegate with its verification status set directly to `accepted`, without sending any verification email. The delegate user must be a member of the same Google Workspace organization as the delegator user. Gmail imposes limitations on the number of delegates and delegators each user in a Google Workspace organization can have. These limits depend on your organization, but in general each user can have up to 25 delegates and up to 10 delegators. Note that a delegate user must be referred to by their primary email address, and not an email alias. Also note that when a new delegate is created, there may be up to a one minute delay before the new delegate is available for use. This method is only available to service account clients that have been delegated domain-wide authority.
2386    ///
2387    /// # Arguments
2388    ///
2389    /// * `request` - No description provided.
2390    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2391    pub fn settings_delegates_create(
2392        &self,
2393        request: Delegate,
2394        user_id: &str,
2395    ) -> UserSettingDelegateCreateCall<'a, C> {
2396        UserSettingDelegateCreateCall {
2397            hub: self.hub,
2398            _request: request,
2399            _user_id: user_id.to_string(),
2400            _delegate: Default::default(),
2401            _additional_params: Default::default(),
2402            _scopes: Default::default(),
2403        }
2404    }
2405
2406    /// Create a builder to help you perform the following task:
2407    ///
2408    /// Removes the specified delegate (which can be of any verification status), and revokes any verification that may have been required for using it. Note that a delegate user must be referred to by their primary email address, and not an email alias. This method is only available to service account clients that have been delegated domain-wide authority.
2409    ///
2410    /// # Arguments
2411    ///
2412    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2413    /// * `delegateEmail` - The email address of the user to be removed as a delegate.
2414    pub fn settings_delegates_delete(
2415        &self,
2416        user_id: &str,
2417        delegate_email: &str,
2418    ) -> UserSettingDelegateDeleteCall<'a, C> {
2419        UserSettingDelegateDeleteCall {
2420            hub: self.hub,
2421            _user_id: user_id.to_string(),
2422            _delegate_email: delegate_email.to_string(),
2423            _delegate: Default::default(),
2424            _additional_params: Default::default(),
2425            _scopes: Default::default(),
2426        }
2427    }
2428
2429    /// Create a builder to help you perform the following task:
2430    ///
2431    /// Gets the specified delegate. Note that a delegate user must be referred to by their primary email address, and not an email alias. This method is only available to service account clients that have been delegated domain-wide authority.
2432    ///
2433    /// # Arguments
2434    ///
2435    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2436    /// * `delegateEmail` - The email address of the user whose delegate relationship is to be retrieved.
2437    pub fn settings_delegates_get(
2438        &self,
2439        user_id: &str,
2440        delegate_email: &str,
2441    ) -> UserSettingDelegateGetCall<'a, C> {
2442        UserSettingDelegateGetCall {
2443            hub: self.hub,
2444            _user_id: user_id.to_string(),
2445            _delegate_email: delegate_email.to_string(),
2446            _delegate: Default::default(),
2447            _additional_params: Default::default(),
2448            _scopes: Default::default(),
2449        }
2450    }
2451
2452    /// Create a builder to help you perform the following task:
2453    ///
2454    /// Lists the delegates for the specified account. This method is only available to service account clients that have been delegated domain-wide authority.
2455    ///
2456    /// # Arguments
2457    ///
2458    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2459    pub fn settings_delegates_list(&self, user_id: &str) -> UserSettingDelegateListCall<'a, C> {
2460        UserSettingDelegateListCall {
2461            hub: self.hub,
2462            _user_id: user_id.to_string(),
2463            _delegate: Default::default(),
2464            _additional_params: Default::default(),
2465            _scopes: Default::default(),
2466        }
2467    }
2468
2469    /// Create a builder to help you perform the following task:
2470    ///
2471    /// Creates a filter. Note: you can only create a maximum of 1,000 filters.
2472    ///
2473    /// # Arguments
2474    ///
2475    /// * `request` - No description provided.
2476    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2477    pub fn settings_filters_create(
2478        &self,
2479        request: Filter,
2480        user_id: &str,
2481    ) -> UserSettingFilterCreateCall<'a, C> {
2482        UserSettingFilterCreateCall {
2483            hub: self.hub,
2484            _request: request,
2485            _user_id: user_id.to_string(),
2486            _delegate: Default::default(),
2487            _additional_params: Default::default(),
2488            _scopes: Default::default(),
2489        }
2490    }
2491
2492    /// Create a builder to help you perform the following task:
2493    ///
2494    /// Immediately and permanently deletes the specified filter.
2495    ///
2496    /// # Arguments
2497    ///
2498    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2499    /// * `id` - The ID of the filter to be deleted.
2500    pub fn settings_filters_delete(
2501        &self,
2502        user_id: &str,
2503        id: &str,
2504    ) -> UserSettingFilterDeleteCall<'a, C> {
2505        UserSettingFilterDeleteCall {
2506            hub: self.hub,
2507            _user_id: user_id.to_string(),
2508            _id: id.to_string(),
2509            _delegate: Default::default(),
2510            _additional_params: Default::default(),
2511            _scopes: Default::default(),
2512        }
2513    }
2514
2515    /// Create a builder to help you perform the following task:
2516    ///
2517    /// Gets a filter.
2518    ///
2519    /// # Arguments
2520    ///
2521    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2522    /// * `id` - The ID of the filter to be fetched.
2523    pub fn settings_filters_get(&self, user_id: &str, id: &str) -> UserSettingFilterGetCall<'a, C> {
2524        UserSettingFilterGetCall {
2525            hub: self.hub,
2526            _user_id: user_id.to_string(),
2527            _id: id.to_string(),
2528            _delegate: Default::default(),
2529            _additional_params: Default::default(),
2530            _scopes: Default::default(),
2531        }
2532    }
2533
2534    /// Create a builder to help you perform the following task:
2535    ///
2536    /// Lists the message filters of a Gmail user.
2537    ///
2538    /// # Arguments
2539    ///
2540    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2541    pub fn settings_filters_list(&self, user_id: &str) -> UserSettingFilterListCall<'a, C> {
2542        UserSettingFilterListCall {
2543            hub: self.hub,
2544            _user_id: user_id.to_string(),
2545            _delegate: Default::default(),
2546            _additional_params: Default::default(),
2547            _scopes: Default::default(),
2548        }
2549    }
2550
2551    /// Create a builder to help you perform the following task:
2552    ///
2553    /// Creates a forwarding address. If ownership verification is required, a message will be sent to the recipient and the resource's verification status will be set to `pending`; otherwise, the resource will be created with verification status set to `accepted`. This method is only available to service account clients that have been delegated domain-wide authority.
2554    ///
2555    /// # Arguments
2556    ///
2557    /// * `request` - No description provided.
2558    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2559    pub fn settings_forwarding_addresses_create(
2560        &self,
2561        request: ForwardingAddress,
2562        user_id: &str,
2563    ) -> UserSettingForwardingAddressCreateCall<'a, C> {
2564        UserSettingForwardingAddressCreateCall {
2565            hub: self.hub,
2566            _request: request,
2567            _user_id: user_id.to_string(),
2568            _delegate: Default::default(),
2569            _additional_params: Default::default(),
2570            _scopes: Default::default(),
2571        }
2572    }
2573
2574    /// Create a builder to help you perform the following task:
2575    ///
2576    /// Deletes the specified forwarding address and revokes any verification that may have been required. This method is only available to service account clients that have been delegated domain-wide authority.
2577    ///
2578    /// # Arguments
2579    ///
2580    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2581    /// * `forwardingEmail` - The forwarding address to be deleted.
2582    pub fn settings_forwarding_addresses_delete(
2583        &self,
2584        user_id: &str,
2585        forwarding_email: &str,
2586    ) -> UserSettingForwardingAddressDeleteCall<'a, C> {
2587        UserSettingForwardingAddressDeleteCall {
2588            hub: self.hub,
2589            _user_id: user_id.to_string(),
2590            _forwarding_email: forwarding_email.to_string(),
2591            _delegate: Default::default(),
2592            _additional_params: Default::default(),
2593            _scopes: Default::default(),
2594        }
2595    }
2596
2597    /// Create a builder to help you perform the following task:
2598    ///
2599    /// Gets the specified forwarding address.
2600    ///
2601    /// # Arguments
2602    ///
2603    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2604    /// * `forwardingEmail` - The forwarding address to be retrieved.
2605    pub fn settings_forwarding_addresses_get(
2606        &self,
2607        user_id: &str,
2608        forwarding_email: &str,
2609    ) -> UserSettingForwardingAddressGetCall<'a, C> {
2610        UserSettingForwardingAddressGetCall {
2611            hub: self.hub,
2612            _user_id: user_id.to_string(),
2613            _forwarding_email: forwarding_email.to_string(),
2614            _delegate: Default::default(),
2615            _additional_params: Default::default(),
2616            _scopes: Default::default(),
2617        }
2618    }
2619
2620    /// Create a builder to help you perform the following task:
2621    ///
2622    /// Lists the forwarding addresses for the specified account.
2623    ///
2624    /// # Arguments
2625    ///
2626    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2627    pub fn settings_forwarding_addresses_list(
2628        &self,
2629        user_id: &str,
2630    ) -> UserSettingForwardingAddressListCall<'a, C> {
2631        UserSettingForwardingAddressListCall {
2632            hub: self.hub,
2633            _user_id: user_id.to_string(),
2634            _delegate: Default::default(),
2635            _additional_params: Default::default(),
2636            _scopes: Default::default(),
2637        }
2638    }
2639
2640    /// Create a builder to help you perform the following task:
2641    ///
2642    /// Deletes the specified S/MIME config for the specified send-as alias.
2643    ///
2644    /// # Arguments
2645    ///
2646    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
2647    /// * `sendAsEmail` - The email address that appears in the "From:" header for mail sent using this alias.
2648    /// * `id` - The immutable ID for the SmimeInfo.
2649    pub fn settings_send_as_smime_info_delete(
2650        &self,
2651        user_id: &str,
2652        send_as_email: &str,
2653        id: &str,
2654    ) -> UserSettingSendASmimeInfoDeleteCall<'a, C> {
2655        UserSettingSendASmimeInfoDeleteCall {
2656            hub: self.hub,
2657            _user_id: user_id.to_string(),
2658            _send_as_email: send_as_email.to_string(),
2659            _id: id.to_string(),
2660            _delegate: Default::default(),
2661            _additional_params: Default::default(),
2662            _scopes: Default::default(),
2663        }
2664    }
2665
2666    /// Create a builder to help you perform the following task:
2667    ///
2668    /// Gets the specified S/MIME config for the specified send-as alias.
2669    ///
2670    /// # Arguments
2671    ///
2672    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
2673    /// * `sendAsEmail` - The email address that appears in the "From:" header for mail sent using this alias.
2674    /// * `id` - The immutable ID for the SmimeInfo.
2675    pub fn settings_send_as_smime_info_get(
2676        &self,
2677        user_id: &str,
2678        send_as_email: &str,
2679        id: &str,
2680    ) -> UserSettingSendASmimeInfoGetCall<'a, C> {
2681        UserSettingSendASmimeInfoGetCall {
2682            hub: self.hub,
2683            _user_id: user_id.to_string(),
2684            _send_as_email: send_as_email.to_string(),
2685            _id: id.to_string(),
2686            _delegate: Default::default(),
2687            _additional_params: Default::default(),
2688            _scopes: Default::default(),
2689        }
2690    }
2691
2692    /// Create a builder to help you perform the following task:
2693    ///
2694    /// Insert (upload) the given S/MIME config for the specified send-as alias. Note that pkcs12 format is required for the key.
2695    ///
2696    /// # Arguments
2697    ///
2698    /// * `request` - No description provided.
2699    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
2700    /// * `sendAsEmail` - The email address that appears in the "From:" header for mail sent using this alias.
2701    pub fn settings_send_as_smime_info_insert(
2702        &self,
2703        request: SmimeInfo,
2704        user_id: &str,
2705        send_as_email: &str,
2706    ) -> UserSettingSendASmimeInfoInsertCall<'a, C> {
2707        UserSettingSendASmimeInfoInsertCall {
2708            hub: self.hub,
2709            _request: request,
2710            _user_id: user_id.to_string(),
2711            _send_as_email: send_as_email.to_string(),
2712            _delegate: Default::default(),
2713            _additional_params: Default::default(),
2714            _scopes: Default::default(),
2715        }
2716    }
2717
2718    /// Create a builder to help you perform the following task:
2719    ///
2720    /// Lists S/MIME configs for the specified send-as alias.
2721    ///
2722    /// # Arguments
2723    ///
2724    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
2725    /// * `sendAsEmail` - The email address that appears in the "From:" header for mail sent using this alias.
2726    pub fn settings_send_as_smime_info_list(
2727        &self,
2728        user_id: &str,
2729        send_as_email: &str,
2730    ) -> UserSettingSendASmimeInfoListCall<'a, C> {
2731        UserSettingSendASmimeInfoListCall {
2732            hub: self.hub,
2733            _user_id: user_id.to_string(),
2734            _send_as_email: send_as_email.to_string(),
2735            _delegate: Default::default(),
2736            _additional_params: Default::default(),
2737            _scopes: Default::default(),
2738        }
2739    }
2740
2741    /// Create a builder to help you perform the following task:
2742    ///
2743    /// Sets the default S/MIME config for the specified send-as alias.
2744    ///
2745    /// # Arguments
2746    ///
2747    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
2748    /// * `sendAsEmail` - The email address that appears in the "From:" header for mail sent using this alias.
2749    /// * `id` - The immutable ID for the SmimeInfo.
2750    pub fn settings_send_as_smime_info_set_default(
2751        &self,
2752        user_id: &str,
2753        send_as_email: &str,
2754        id: &str,
2755    ) -> UserSettingSendASmimeInfoSetDefaultCall<'a, C> {
2756        UserSettingSendASmimeInfoSetDefaultCall {
2757            hub: self.hub,
2758            _user_id: user_id.to_string(),
2759            _send_as_email: send_as_email.to_string(),
2760            _id: id.to_string(),
2761            _delegate: Default::default(),
2762            _additional_params: Default::default(),
2763            _scopes: Default::default(),
2764        }
2765    }
2766
2767    /// Create a builder to help you perform the following task:
2768    ///
2769    /// Creates a custom "from" send-as alias. If an SMTP MSA is specified, Gmail will attempt to connect to the SMTP service to validate the configuration before creating the alias. If ownership verification is required for the alias, a message will be sent to the email address and the resource's verification status will be set to `pending`; otherwise, the resource will be created with verification status set to `accepted`. If a signature is provided, Gmail will sanitize the HTML before saving it with the alias. This method is only available to service account clients that have been delegated domain-wide authority.
2770    ///
2771    /// # Arguments
2772    ///
2773    /// * `request` - No description provided.
2774    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2775    pub fn settings_send_as_create(
2776        &self,
2777        request: SendAs,
2778        user_id: &str,
2779    ) -> UserSettingSendACreateCall<'a, C> {
2780        UserSettingSendACreateCall {
2781            hub: self.hub,
2782            _request: request,
2783            _user_id: user_id.to_string(),
2784            _delegate: Default::default(),
2785            _additional_params: Default::default(),
2786            _scopes: Default::default(),
2787        }
2788    }
2789
2790    /// Create a builder to help you perform the following task:
2791    ///
2792    /// Deletes the specified send-as alias. Revokes any verification that may have been required for using it. This method is only available to service account clients that have been delegated domain-wide authority.
2793    ///
2794    /// # Arguments
2795    ///
2796    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2797    /// * `sendAsEmail` - The send-as alias to be deleted.
2798    pub fn settings_send_as_delete(
2799        &self,
2800        user_id: &str,
2801        send_as_email: &str,
2802    ) -> UserSettingSendADeleteCall<'a, C> {
2803        UserSettingSendADeleteCall {
2804            hub: self.hub,
2805            _user_id: user_id.to_string(),
2806            _send_as_email: send_as_email.to_string(),
2807            _delegate: Default::default(),
2808            _additional_params: Default::default(),
2809            _scopes: Default::default(),
2810        }
2811    }
2812
2813    /// Create a builder to help you perform the following task:
2814    ///
2815    /// Gets the specified send-as alias. Fails with an HTTP 404 error if the specified address is not a member of the collection.
2816    ///
2817    /// # Arguments
2818    ///
2819    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2820    /// * `sendAsEmail` - The send-as alias to be retrieved.
2821    pub fn settings_send_as_get(
2822        &self,
2823        user_id: &str,
2824        send_as_email: &str,
2825    ) -> UserSettingSendAGetCall<'a, C> {
2826        UserSettingSendAGetCall {
2827            hub: self.hub,
2828            _user_id: user_id.to_string(),
2829            _send_as_email: send_as_email.to_string(),
2830            _delegate: Default::default(),
2831            _additional_params: Default::default(),
2832            _scopes: Default::default(),
2833        }
2834    }
2835
2836    /// Create a builder to help you perform the following task:
2837    ///
2838    /// Lists the send-as aliases for the specified account. The result includes the primary send-as address associated with the account as well as any custom "from" aliases.
2839    ///
2840    /// # Arguments
2841    ///
2842    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2843    pub fn settings_send_as_list(&self, user_id: &str) -> UserSettingSendAListCall<'a, C> {
2844        UserSettingSendAListCall {
2845            hub: self.hub,
2846            _user_id: user_id.to_string(),
2847            _delegate: Default::default(),
2848            _additional_params: Default::default(),
2849            _scopes: Default::default(),
2850        }
2851    }
2852
2853    /// Create a builder to help you perform the following task:
2854    ///
2855    /// Patch the specified send-as alias.
2856    ///
2857    /// # Arguments
2858    ///
2859    /// * `request` - No description provided.
2860    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2861    /// * `sendAsEmail` - The send-as alias to be updated.
2862    pub fn settings_send_as_patch(
2863        &self,
2864        request: SendAs,
2865        user_id: &str,
2866        send_as_email: &str,
2867    ) -> UserSettingSendAPatchCall<'a, C> {
2868        UserSettingSendAPatchCall {
2869            hub: self.hub,
2870            _request: request,
2871            _user_id: user_id.to_string(),
2872            _send_as_email: send_as_email.to_string(),
2873            _delegate: Default::default(),
2874            _additional_params: Default::default(),
2875            _scopes: Default::default(),
2876        }
2877    }
2878
2879    /// Create a builder to help you perform the following task:
2880    ///
2881    /// Updates a send-as alias. If a signature is provided, Gmail will sanitize the HTML before saving it with the alias. Addresses other than the primary address for the account can only be updated by service account clients that have been delegated domain-wide authority.
2882    ///
2883    /// # Arguments
2884    ///
2885    /// * `request` - No description provided.
2886    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2887    /// * `sendAsEmail` - The send-as alias to be updated.
2888    pub fn settings_send_as_update(
2889        &self,
2890        request: SendAs,
2891        user_id: &str,
2892        send_as_email: &str,
2893    ) -> UserSettingSendAUpdateCall<'a, C> {
2894        UserSettingSendAUpdateCall {
2895            hub: self.hub,
2896            _request: request,
2897            _user_id: user_id.to_string(),
2898            _send_as_email: send_as_email.to_string(),
2899            _delegate: Default::default(),
2900            _additional_params: Default::default(),
2901            _scopes: Default::default(),
2902        }
2903    }
2904
2905    /// Create a builder to help you perform the following task:
2906    ///
2907    /// Sends a verification email to the specified send-as alias address. The verification status must be `pending`. This method is only available to service account clients that have been delegated domain-wide authority.
2908    ///
2909    /// # Arguments
2910    ///
2911    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2912    /// * `sendAsEmail` - The send-as alias to be verified.
2913    pub fn settings_send_as_verify(
2914        &self,
2915        user_id: &str,
2916        send_as_email: &str,
2917    ) -> UserSettingSendAVerifyCall<'a, C> {
2918        UserSettingSendAVerifyCall {
2919            hub: self.hub,
2920            _user_id: user_id.to_string(),
2921            _send_as_email: send_as_email.to_string(),
2922            _delegate: Default::default(),
2923            _additional_params: Default::default(),
2924            _scopes: Default::default(),
2925        }
2926    }
2927
2928    /// Create a builder to help you perform the following task:
2929    ///
2930    /// Gets the auto-forwarding setting for the specified account.
2931    ///
2932    /// # Arguments
2933    ///
2934    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2935    pub fn settings_get_auto_forwarding(
2936        &self,
2937        user_id: &str,
2938    ) -> UserSettingGetAutoForwardingCall<'a, C> {
2939        UserSettingGetAutoForwardingCall {
2940            hub: self.hub,
2941            _user_id: user_id.to_string(),
2942            _delegate: Default::default(),
2943            _additional_params: Default::default(),
2944            _scopes: Default::default(),
2945        }
2946    }
2947
2948    /// Create a builder to help you perform the following task:
2949    ///
2950    /// Gets IMAP settings.
2951    ///
2952    /// # Arguments
2953    ///
2954    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2955    pub fn settings_get_imap(&self, user_id: &str) -> UserSettingGetImapCall<'a, C> {
2956        UserSettingGetImapCall {
2957            hub: self.hub,
2958            _user_id: user_id.to_string(),
2959            _delegate: Default::default(),
2960            _additional_params: Default::default(),
2961            _scopes: Default::default(),
2962        }
2963    }
2964
2965    /// Create a builder to help you perform the following task:
2966    ///
2967    /// Gets language settings.
2968    ///
2969    /// # Arguments
2970    ///
2971    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2972    pub fn settings_get_language(&self, user_id: &str) -> UserSettingGetLanguageCall<'a, C> {
2973        UserSettingGetLanguageCall {
2974            hub: self.hub,
2975            _user_id: user_id.to_string(),
2976            _delegate: Default::default(),
2977            _additional_params: Default::default(),
2978            _scopes: Default::default(),
2979        }
2980    }
2981
2982    /// Create a builder to help you perform the following task:
2983    ///
2984    /// Gets POP settings.
2985    ///
2986    /// # Arguments
2987    ///
2988    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
2989    pub fn settings_get_pop(&self, user_id: &str) -> UserSettingGetPopCall<'a, C> {
2990        UserSettingGetPopCall {
2991            hub: self.hub,
2992            _user_id: user_id.to_string(),
2993            _delegate: Default::default(),
2994            _additional_params: Default::default(),
2995            _scopes: Default::default(),
2996        }
2997    }
2998
2999    /// Create a builder to help you perform the following task:
3000    ///
3001    /// Gets vacation responder settings.
3002    ///
3003    /// # Arguments
3004    ///
3005    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
3006    pub fn settings_get_vacation(&self, user_id: &str) -> UserSettingGetVacationCall<'a, C> {
3007        UserSettingGetVacationCall {
3008            hub: self.hub,
3009            _user_id: user_id.to_string(),
3010            _delegate: Default::default(),
3011            _additional_params: Default::default(),
3012            _scopes: Default::default(),
3013        }
3014    }
3015
3016    /// Create a builder to help you perform the following task:
3017    ///
3018    /// Updates the auto-forwarding setting for the specified account. A verified forwarding address must be specified when auto-forwarding is enabled. This method is only available to service account clients that have been delegated domain-wide authority.
3019    ///
3020    /// # Arguments
3021    ///
3022    /// * `request` - No description provided.
3023    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
3024    pub fn settings_update_auto_forwarding(
3025        &self,
3026        request: AutoForwarding,
3027        user_id: &str,
3028    ) -> UserSettingUpdateAutoForwardingCall<'a, C> {
3029        UserSettingUpdateAutoForwardingCall {
3030            hub: self.hub,
3031            _request: request,
3032            _user_id: user_id.to_string(),
3033            _delegate: Default::default(),
3034            _additional_params: Default::default(),
3035            _scopes: Default::default(),
3036        }
3037    }
3038
3039    /// Create a builder to help you perform the following task:
3040    ///
3041    /// Updates IMAP settings.
3042    ///
3043    /// # Arguments
3044    ///
3045    /// * `request` - No description provided.
3046    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
3047    pub fn settings_update_imap(
3048        &self,
3049        request: ImapSettings,
3050        user_id: &str,
3051    ) -> UserSettingUpdateImapCall<'a, C> {
3052        UserSettingUpdateImapCall {
3053            hub: self.hub,
3054            _request: request,
3055            _user_id: user_id.to_string(),
3056            _delegate: Default::default(),
3057            _additional_params: Default::default(),
3058            _scopes: Default::default(),
3059        }
3060    }
3061
3062    /// Create a builder to help you perform the following task:
3063    ///
3064    /// Updates language settings. If successful, the return object contains the `displayLanguage` that was saved for the user, which may differ from the value passed into the request. This is because the requested `displayLanguage` may not be directly supported by Gmail but have a close variant that is, and so the variant may be chosen and saved instead.
3065    ///
3066    /// # Arguments
3067    ///
3068    /// * `request` - No description provided.
3069    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
3070    pub fn settings_update_language(
3071        &self,
3072        request: LanguageSettings,
3073        user_id: &str,
3074    ) -> UserSettingUpdateLanguageCall<'a, C> {
3075        UserSettingUpdateLanguageCall {
3076            hub: self.hub,
3077            _request: request,
3078            _user_id: user_id.to_string(),
3079            _delegate: Default::default(),
3080            _additional_params: Default::default(),
3081            _scopes: Default::default(),
3082        }
3083    }
3084
3085    /// Create a builder to help you perform the following task:
3086    ///
3087    /// Updates POP settings.
3088    ///
3089    /// # Arguments
3090    ///
3091    /// * `request` - No description provided.
3092    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
3093    pub fn settings_update_pop(
3094        &self,
3095        request: PopSettings,
3096        user_id: &str,
3097    ) -> UserSettingUpdatePopCall<'a, C> {
3098        UserSettingUpdatePopCall {
3099            hub: self.hub,
3100            _request: request,
3101            _user_id: user_id.to_string(),
3102            _delegate: Default::default(),
3103            _additional_params: Default::default(),
3104            _scopes: Default::default(),
3105        }
3106    }
3107
3108    /// Create a builder to help you perform the following task:
3109    ///
3110    /// Updates vacation responder settings.
3111    ///
3112    /// # Arguments
3113    ///
3114    /// * `request` - No description provided.
3115    /// * `userId` - User's email address. The special value "me" can be used to indicate the authenticated user.
3116    pub fn settings_update_vacation(
3117        &self,
3118        request: VacationSettings,
3119        user_id: &str,
3120    ) -> UserSettingUpdateVacationCall<'a, C> {
3121        UserSettingUpdateVacationCall {
3122            hub: self.hub,
3123            _request: request,
3124            _user_id: user_id.to_string(),
3125            _delegate: Default::default(),
3126            _additional_params: Default::default(),
3127            _scopes: Default::default(),
3128        }
3129    }
3130
3131    /// Create a builder to help you perform the following task:
3132    ///
3133    /// Immediately and permanently deletes the specified thread. Any messages that belong to the thread are also deleted. This operation cannot be undone. Prefer `threads.trash` instead.
3134    ///
3135    /// # Arguments
3136    ///
3137    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
3138    /// * `id` - ID of the Thread to delete.
3139    pub fn threads_delete(&self, user_id: &str, id: &str) -> UserThreadDeleteCall<'a, C> {
3140        UserThreadDeleteCall {
3141            hub: self.hub,
3142            _user_id: user_id.to_string(),
3143            _id: id.to_string(),
3144            _delegate: Default::default(),
3145            _additional_params: Default::default(),
3146            _scopes: Default::default(),
3147        }
3148    }
3149
3150    /// Create a builder to help you perform the following task:
3151    ///
3152    /// Gets the specified thread.
3153    ///
3154    /// # Arguments
3155    ///
3156    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
3157    /// * `id` - The ID of the thread to retrieve.
3158    pub fn threads_get(&self, user_id: &str, id: &str) -> UserThreadGetCall<'a, C> {
3159        UserThreadGetCall {
3160            hub: self.hub,
3161            _user_id: user_id.to_string(),
3162            _id: id.to_string(),
3163            _metadata_headers: Default::default(),
3164            _format: Default::default(),
3165            _delegate: Default::default(),
3166            _additional_params: Default::default(),
3167            _scopes: Default::default(),
3168        }
3169    }
3170
3171    /// Create a builder to help you perform the following task:
3172    ///
3173    /// Lists the threads in the user's mailbox.
3174    ///
3175    /// # Arguments
3176    ///
3177    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
3178    pub fn threads_list(&self, user_id: &str) -> UserThreadListCall<'a, C> {
3179        UserThreadListCall {
3180            hub: self.hub,
3181            _user_id: user_id.to_string(),
3182            _q: Default::default(),
3183            _page_token: Default::default(),
3184            _max_results: Default::default(),
3185            _label_ids: Default::default(),
3186            _include_spam_trash: Default::default(),
3187            _delegate: Default::default(),
3188            _additional_params: Default::default(),
3189            _scopes: Default::default(),
3190        }
3191    }
3192
3193    /// Create a builder to help you perform the following task:
3194    ///
3195    /// Modifies the labels applied to the thread. This applies to all messages in the thread.
3196    ///
3197    /// # Arguments
3198    ///
3199    /// * `request` - No description provided.
3200    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
3201    /// * `id` - The ID of the thread to modify.
3202    pub fn threads_modify(
3203        &self,
3204        request: ModifyThreadRequest,
3205        user_id: &str,
3206        id: &str,
3207    ) -> UserThreadModifyCall<'a, C> {
3208        UserThreadModifyCall {
3209            hub: self.hub,
3210            _request: request,
3211            _user_id: user_id.to_string(),
3212            _id: id.to_string(),
3213            _delegate: Default::default(),
3214            _additional_params: Default::default(),
3215            _scopes: Default::default(),
3216        }
3217    }
3218
3219    /// Create a builder to help you perform the following task:
3220    ///
3221    /// Moves the specified thread to the trash. Any messages that belong to the thread are also moved to the trash.
3222    ///
3223    /// # Arguments
3224    ///
3225    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
3226    /// * `id` - The ID of the thread to Trash.
3227    pub fn threads_trash(&self, user_id: &str, id: &str) -> UserThreadTrashCall<'a, C> {
3228        UserThreadTrashCall {
3229            hub: self.hub,
3230            _user_id: user_id.to_string(),
3231            _id: id.to_string(),
3232            _delegate: Default::default(),
3233            _additional_params: Default::default(),
3234            _scopes: Default::default(),
3235        }
3236    }
3237
3238    /// Create a builder to help you perform the following task:
3239    ///
3240    /// Removes the specified thread from the trash. Any messages that belong to the thread are also removed from the trash.
3241    ///
3242    /// # Arguments
3243    ///
3244    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
3245    /// * `id` - The ID of the thread to remove from Trash.
3246    pub fn threads_untrash(&self, user_id: &str, id: &str) -> UserThreadUntrashCall<'a, C> {
3247        UserThreadUntrashCall {
3248            hub: self.hub,
3249            _user_id: user_id.to_string(),
3250            _id: id.to_string(),
3251            _delegate: Default::default(),
3252            _additional_params: Default::default(),
3253            _scopes: Default::default(),
3254        }
3255    }
3256
3257    /// Create a builder to help you perform the following task:
3258    ///
3259    /// Gets the current user's Gmail profile.
3260    ///
3261    /// # Arguments
3262    ///
3263    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
3264    pub fn get_profile(&self, user_id: &str) -> UserGetProfileCall<'a, C> {
3265        UserGetProfileCall {
3266            hub: self.hub,
3267            _user_id: user_id.to_string(),
3268            _delegate: Default::default(),
3269            _additional_params: Default::default(),
3270            _scopes: Default::default(),
3271        }
3272    }
3273
3274    /// Create a builder to help you perform the following task:
3275    ///
3276    /// Stop receiving push notifications for the given user mailbox.
3277    ///
3278    /// # Arguments
3279    ///
3280    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
3281    pub fn stop(&self, user_id: &str) -> UserStopCall<'a, C> {
3282        UserStopCall {
3283            hub: self.hub,
3284            _user_id: user_id.to_string(),
3285            _delegate: Default::default(),
3286            _additional_params: Default::default(),
3287            _scopes: Default::default(),
3288        }
3289    }
3290
3291    /// Create a builder to help you perform the following task:
3292    ///
3293    /// Set up or update a push notification watch on the given user mailbox.
3294    ///
3295    /// # Arguments
3296    ///
3297    /// * `request` - No description provided.
3298    /// * `userId` - The user's email address. The special value `me` can be used to indicate the authenticated user.
3299    pub fn watch(&self, request: WatchRequest, user_id: &str) -> UserWatchCall<'a, C> {
3300        UserWatchCall {
3301            hub: self.hub,
3302            _request: request,
3303            _user_id: user_id.to_string(),
3304            _delegate: Default::default(),
3305            _additional_params: Default::default(),
3306            _scopes: Default::default(),
3307        }
3308    }
3309}
3310
3311// ###################
3312// CallBuilders   ###
3313// #################
3314
3315/// Creates a new draft with the `DRAFT` label.
3316///
3317/// A builder for the *drafts.create* method supported by a *user* resource.
3318/// It is not used directly, but through a [`UserMethods`] instance.
3319///
3320/// # Example
3321///
3322/// Instantiate a resource method builder
3323///
3324/// ```test_harness,no_run
3325/// # extern crate hyper;
3326/// # extern crate hyper_rustls;
3327/// # extern crate google_gmail1 as gmail1;
3328/// use gmail1::api::Draft;
3329/// use std::fs;
3330/// # async fn dox() {
3331/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
3332///
3333/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
3334/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
3335/// #     secret,
3336/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
3337/// # ).build().await.unwrap();
3338///
3339/// # let client = hyper_util::client::legacy::Client::builder(
3340/// #     hyper_util::rt::TokioExecutor::new()
3341/// # )
3342/// # .build(
3343/// #     hyper_rustls::HttpsConnectorBuilder::new()
3344/// #         .with_native_roots()
3345/// #         .unwrap()
3346/// #         .https_or_http()
3347/// #         .enable_http1()
3348/// #         .build()
3349/// # );
3350/// # let mut hub = Gmail::new(client, auth);
3351/// // As the method needs a request, you would usually fill it with the desired information
3352/// // into the respective structure. Some of the parts shown here might not be applicable !
3353/// // Values shown here are possibly random and not representative !
3354/// let mut req = Draft::default();
3355///
3356/// // You can configure optional parameters by calling the respective setters at will, and
3357/// // execute the final call using `upload_resumable(...)`.
3358/// // Values shown here are possibly random and not representative !
3359/// let result = hub.users().drafts_create(req, "userId")
3360///              .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()).await;
3361/// # }
3362/// ```
3363pub struct UserDraftCreateCall<'a, C>
3364where
3365    C: 'a,
3366{
3367    hub: &'a Gmail<C>,
3368    _request: Draft,
3369    _user_id: String,
3370    _delegate: Option<&'a mut dyn common::Delegate>,
3371    _additional_params: HashMap<String, String>,
3372    _scopes: BTreeSet<String>,
3373}
3374
3375impl<'a, C> common::CallBuilder for UserDraftCreateCall<'a, C> {}
3376
3377impl<'a, C> UserDraftCreateCall<'a, C>
3378where
3379    C: common::Connector,
3380{
3381    /// Perform the operation you have build so far.
3382    async fn doit<RS>(
3383        mut self,
3384        mut reader: RS,
3385        reader_mime_type: mime::Mime,
3386        protocol: common::UploadProtocol,
3387    ) -> common::Result<(common::Response, Draft)>
3388    where
3389        RS: common::ReadSeek,
3390    {
3391        use std::borrow::Cow;
3392        use std::io::{Read, Seek};
3393
3394        use common::{url::Params, ToParts};
3395        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
3396
3397        let mut dd = common::DefaultDelegate;
3398        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
3399        dlg.begin(common::MethodInfo {
3400            id: "gmail.users.drafts.create",
3401            http_method: hyper::Method::POST,
3402        });
3403
3404        for &field in ["alt", "userId"].iter() {
3405            if self._additional_params.contains_key(field) {
3406                dlg.finished(false);
3407                return Err(common::Error::FieldClash(field));
3408            }
3409        }
3410
3411        let mut params = Params::with_capacity(4 + self._additional_params.len());
3412        params.push("userId", self._user_id);
3413
3414        params.extend(self._additional_params.iter());
3415
3416        params.push("alt", "json");
3417        let (mut url, upload_type) = if protocol == common::UploadProtocol::Resumable {
3418            (
3419                self.hub._root_url.clone() + "resumable/upload/gmail/v1/users/{userId}/drafts",
3420                "resumable",
3421            )
3422        } else if protocol == common::UploadProtocol::Simple {
3423            (
3424                self.hub._root_url.clone() + "upload/gmail/v1/users/{userId}/drafts",
3425                "multipart",
3426            )
3427        } else {
3428            unreachable!()
3429        };
3430        params.push("uploadType", upload_type);
3431        if self._scopes.is_empty() {
3432            self._scopes.insert(Scope::Gmai.as_ref().to_string());
3433        }
3434
3435        #[allow(clippy::single_element_loop)]
3436        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
3437            url = params.uri_replacement(url, param_name, find_this, false);
3438        }
3439        {
3440            let to_remove = ["userId"];
3441            params.remove_params(&to_remove);
3442        }
3443
3444        let url = params.parse_with_url(&url);
3445
3446        let mut json_mime_type = mime::APPLICATION_JSON;
3447        let mut request_value_reader = {
3448            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
3449            common::remove_json_null_values(&mut value);
3450            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
3451            serde_json::to_writer(&mut dst, &value).unwrap();
3452            dst
3453        };
3454        let request_size = request_value_reader
3455            .seek(std::io::SeekFrom::End(0))
3456            .unwrap();
3457        request_value_reader
3458            .seek(std::io::SeekFrom::Start(0))
3459            .unwrap();
3460
3461        let mut upload_url_from_server;
3462
3463        loop {
3464            let token = match self
3465                .hub
3466                .auth
3467                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
3468                .await
3469            {
3470                Ok(token) => token,
3471                Err(e) => match dlg.token(e) {
3472                    Ok(token) => token,
3473                    Err(e) => {
3474                        dlg.finished(false);
3475                        return Err(common::Error::MissingToken(e));
3476                    }
3477                },
3478            };
3479            request_value_reader
3480                .seek(std::io::SeekFrom::Start(0))
3481                .unwrap();
3482            let mut req_result = {
3483                let mut mp_reader: common::MultiPartReader = Default::default();
3484                let (mut body_reader, content_type) = match protocol {
3485                    common::UploadProtocol::Simple => {
3486                        mp_reader.reserve_exact(2);
3487                        let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
3488                        reader.seek(std::io::SeekFrom::Start(0)).unwrap();
3489                        if size > 36700160 {
3490                            return Err(common::Error::UploadSizeLimitExceeded(size, 36700160));
3491                        }
3492                        mp_reader
3493                            .add_part(
3494                                &mut request_value_reader,
3495                                request_size,
3496                                json_mime_type.clone(),
3497                            )
3498                            .add_part(&mut reader, size, reader_mime_type.clone());
3499                        (
3500                            &mut mp_reader as &mut (dyn std::io::Read + Send),
3501                            common::MultiPartReader::mime_type(),
3502                        )
3503                    }
3504                    _ => (
3505                        &mut request_value_reader as &mut (dyn std::io::Read + Send),
3506                        json_mime_type.clone(),
3507                    ),
3508                };
3509                let client = &self.hub.client;
3510                dlg.pre_request();
3511                let mut req_builder = hyper::Request::builder()
3512                    .method(hyper::Method::POST)
3513                    .uri(url.as_str())
3514                    .header(USER_AGENT, self.hub._user_agent.clone());
3515
3516                if let Some(token) = token.as_ref() {
3517                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
3518                }
3519
3520                upload_url_from_server = true;
3521                if protocol == common::UploadProtocol::Resumable {
3522                    req_builder = req_builder
3523                        .header("X-Upload-Content-Type", format!("{}", reader_mime_type));
3524                }
3525
3526                let mut body_reader_bytes = vec![];
3527                body_reader.read_to_end(&mut body_reader_bytes).unwrap();
3528                let request = req_builder
3529                    .header(CONTENT_TYPE, content_type.to_string())
3530                    .body(common::to_body(body_reader_bytes.into()));
3531
3532                client.request(request.unwrap()).await
3533            };
3534
3535            match req_result {
3536                Err(err) => {
3537                    if let common::Retry::After(d) = dlg.http_error(&err) {
3538                        sleep(d).await;
3539                        continue;
3540                    }
3541                    dlg.finished(false);
3542                    return Err(common::Error::HttpError(err));
3543                }
3544                Ok(res) => {
3545                    let (mut parts, body) = res.into_parts();
3546                    let mut body = common::Body::new(body);
3547                    if !parts.status.is_success() {
3548                        let bytes = common::to_bytes(body).await.unwrap_or_default();
3549                        let error = serde_json::from_str(&common::to_string(&bytes));
3550                        let response = common::to_response(parts, bytes.into());
3551
3552                        if let common::Retry::After(d) =
3553                            dlg.http_failure(&response, error.as_ref().ok())
3554                        {
3555                            sleep(d).await;
3556                            continue;
3557                        }
3558
3559                        dlg.finished(false);
3560
3561                        return Err(match error {
3562                            Ok(value) => common::Error::BadRequest(value),
3563                            _ => common::Error::Failure(response),
3564                        });
3565                    }
3566                    if protocol == common::UploadProtocol::Resumable {
3567                        let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
3568                        reader.seek(std::io::SeekFrom::Start(0)).unwrap();
3569                        if size > 36700160 {
3570                            return Err(common::Error::UploadSizeLimitExceeded(size, 36700160));
3571                        }
3572                        let upload_result = {
3573                            let url_str = &parts
3574                                .headers
3575                                .get("Location")
3576                                .expect("LOCATION header is part of protocol")
3577                                .to_str()
3578                                .unwrap();
3579                            if upload_url_from_server {
3580                                dlg.store_upload_url(Some(url_str));
3581                            }
3582
3583                            common::ResumableUploadHelper {
3584                                client: &self.hub.client,
3585                                delegate: dlg,
3586                                start_at: if upload_url_from_server {
3587                                    Some(0)
3588                                } else {
3589                                    None
3590                                },
3591                                auth: &self.hub.auth,
3592                                user_agent: &self.hub._user_agent,
3593                                // TODO: Check this assumption
3594                                auth_header: format!(
3595                                    "Bearer {}",
3596                                    token
3597                                        .ok_or_else(|| common::Error::MissingToken(
3598                                            "resumable upload requires token".into()
3599                                        ))?
3600                                        .as_str()
3601                                ),
3602                                url: url_str,
3603                                reader: &mut reader,
3604                                media_type: reader_mime_type.clone(),
3605                                content_length: size,
3606                            }
3607                            .upload()
3608                            .await
3609                        };
3610                        match upload_result {
3611                            None => {
3612                                dlg.finished(false);
3613                                return Err(common::Error::Cancelled);
3614                            }
3615                            Some(Err(err)) => {
3616                                dlg.finished(false);
3617                                return Err(common::Error::HttpError(err));
3618                            }
3619                            Some(Ok(response)) => {
3620                                (parts, body) = response.into_parts();
3621                                if !parts.status.is_success() {
3622                                    dlg.store_upload_url(None);
3623                                    dlg.finished(false);
3624                                    return Err(common::Error::Failure(
3625                                        common::Response::from_parts(parts, body),
3626                                    ));
3627                                }
3628                            }
3629                        }
3630                    }
3631                    let response = {
3632                        let bytes = common::to_bytes(body).await.unwrap_or_default();
3633                        let encoded = common::to_string(&bytes);
3634                        match serde_json::from_str(&encoded) {
3635                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
3636                            Err(error) => {
3637                                dlg.response_json_decode_error(&encoded, &error);
3638                                return Err(common::Error::JsonDecodeError(
3639                                    encoded.to_string(),
3640                                    error,
3641                                ));
3642                            }
3643                        }
3644                    };
3645
3646                    dlg.finished(true);
3647                    return Ok(response);
3648                }
3649            }
3650        }
3651    }
3652
3653    /// Upload media in a resumable fashion.
3654    /// Even if the upload fails or is interrupted, it can be resumed for a
3655    /// certain amount of time as the server maintains state temporarily.
3656    ///
3657    /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL
3658    /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate
3659    /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using
3660    /// `cancel_chunk_upload(...)`.
3661    ///
3662    /// * *multipart*: yes
3663    /// * *max size*: 36700160
3664    /// * *valid mime types*: 'message/*'
3665    pub async fn upload_resumable<RS>(
3666        self,
3667        resumeable_stream: RS,
3668        mime_type: mime::Mime,
3669    ) -> common::Result<(common::Response, Draft)>
3670    where
3671        RS: common::ReadSeek,
3672    {
3673        self.doit(
3674            resumeable_stream,
3675            mime_type,
3676            common::UploadProtocol::Resumable,
3677        )
3678        .await
3679    }
3680    /// Upload media all at once.
3681    /// If the upload fails for whichever reason, all progress is lost.
3682    ///
3683    /// * *multipart*: yes
3684    /// * *max size*: 36700160
3685    /// * *valid mime types*: 'message/*'
3686    pub async fn upload<RS>(
3687        self,
3688        stream: RS,
3689        mime_type: mime::Mime,
3690    ) -> common::Result<(common::Response, Draft)>
3691    where
3692        RS: common::ReadSeek,
3693    {
3694        self.doit(stream, mime_type, common::UploadProtocol::Simple)
3695            .await
3696    }
3697
3698    ///
3699    /// Sets the *request* property to the given value.
3700    ///
3701    /// Even though the property as already been set when instantiating this call,
3702    /// we provide this method for API completeness.
3703    pub fn request(mut self, new_value: Draft) -> UserDraftCreateCall<'a, C> {
3704        self._request = new_value;
3705        self
3706    }
3707    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
3708    ///
3709    /// Sets the *user id* path property to the given value.
3710    ///
3711    /// Even though the property as already been set when instantiating this call,
3712    /// we provide this method for API completeness.
3713    pub fn user_id(mut self, new_value: &str) -> UserDraftCreateCall<'a, C> {
3714        self._user_id = new_value.to_string();
3715        self
3716    }
3717    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
3718    /// while executing the actual API request.
3719    ///
3720    /// ````text
3721    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
3722    /// ````
3723    ///
3724    /// Sets the *delegate* property to the given value.
3725    pub fn delegate(
3726        mut self,
3727        new_value: &'a mut dyn common::Delegate,
3728    ) -> UserDraftCreateCall<'a, C> {
3729        self._delegate = Some(new_value);
3730        self
3731    }
3732
3733    /// Set any additional parameter of the query string used in the request.
3734    /// It should be used to set parameters which are not yet available through their own
3735    /// setters.
3736    ///
3737    /// Please note that this method must not be used to set any of the known parameters
3738    /// which have their own setter method. If done anyway, the request will fail.
3739    ///
3740    /// # Additional Parameters
3741    ///
3742    /// * *$.xgafv* (query-string) - V1 error format.
3743    /// * *access_token* (query-string) - OAuth access token.
3744    /// * *alt* (query-string) - Data format for response.
3745    /// * *callback* (query-string) - JSONP
3746    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
3747    /// * *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.
3748    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
3749    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
3750    /// * *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.
3751    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
3752    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
3753    pub fn param<T>(mut self, name: T, value: T) -> UserDraftCreateCall<'a, C>
3754    where
3755        T: AsRef<str>,
3756    {
3757        self._additional_params
3758            .insert(name.as_ref().to_string(), value.as_ref().to_string());
3759        self
3760    }
3761
3762    /// Identifies the authorization scope for the method you are building.
3763    ///
3764    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
3765    /// [`Scope::Gmai`].
3766    ///
3767    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
3768    /// tokens for more than one scope.
3769    ///
3770    /// Usually there is more than one suitable scope to authorize an operation, some of which may
3771    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
3772    /// sufficient, a read-write scope will do as well.
3773    pub fn add_scope<St>(mut self, scope: St) -> UserDraftCreateCall<'a, C>
3774    where
3775        St: AsRef<str>,
3776    {
3777        self._scopes.insert(String::from(scope.as_ref()));
3778        self
3779    }
3780    /// Identifies the authorization scope(s) for the method you are building.
3781    ///
3782    /// See [`Self::add_scope()`] for details.
3783    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserDraftCreateCall<'a, C>
3784    where
3785        I: IntoIterator<Item = St>,
3786        St: AsRef<str>,
3787    {
3788        self._scopes
3789            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
3790        self
3791    }
3792
3793    /// Removes all scopes, and no default scope will be used either.
3794    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
3795    /// for details).
3796    pub fn clear_scopes(mut self) -> UserDraftCreateCall<'a, C> {
3797        self._scopes.clear();
3798        self
3799    }
3800}
3801
3802/// Immediately and permanently deletes the specified draft. Does not simply trash it.
3803///
3804/// A builder for the *drafts.delete* method supported by a *user* resource.
3805/// It is not used directly, but through a [`UserMethods`] instance.
3806///
3807/// # Example
3808///
3809/// Instantiate a resource method builder
3810///
3811/// ```test_harness,no_run
3812/// # extern crate hyper;
3813/// # extern crate hyper_rustls;
3814/// # extern crate google_gmail1 as gmail1;
3815/// # async fn dox() {
3816/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
3817///
3818/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
3819/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
3820/// #     secret,
3821/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
3822/// # ).build().await.unwrap();
3823///
3824/// # let client = hyper_util::client::legacy::Client::builder(
3825/// #     hyper_util::rt::TokioExecutor::new()
3826/// # )
3827/// # .build(
3828/// #     hyper_rustls::HttpsConnectorBuilder::new()
3829/// #         .with_native_roots()
3830/// #         .unwrap()
3831/// #         .https_or_http()
3832/// #         .enable_http1()
3833/// #         .build()
3834/// # );
3835/// # let mut hub = Gmail::new(client, auth);
3836/// // You can configure optional parameters by calling the respective setters at will, and
3837/// // execute the final call using `doit()`.
3838/// // Values shown here are possibly random and not representative !
3839/// let result = hub.users().drafts_delete("userId", "id")
3840///              .doit().await;
3841/// # }
3842/// ```
3843pub struct UserDraftDeleteCall<'a, C>
3844where
3845    C: 'a,
3846{
3847    hub: &'a Gmail<C>,
3848    _user_id: String,
3849    _id: String,
3850    _delegate: Option<&'a mut dyn common::Delegate>,
3851    _additional_params: HashMap<String, String>,
3852    _scopes: BTreeSet<String>,
3853}
3854
3855impl<'a, C> common::CallBuilder for UserDraftDeleteCall<'a, C> {}
3856
3857impl<'a, C> UserDraftDeleteCall<'a, C>
3858where
3859    C: common::Connector,
3860{
3861    /// Perform the operation you have build so far.
3862    pub async fn doit(mut self) -> common::Result<common::Response> {
3863        use std::borrow::Cow;
3864        use std::io::{Read, Seek};
3865
3866        use common::{url::Params, ToParts};
3867        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
3868
3869        let mut dd = common::DefaultDelegate;
3870        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
3871        dlg.begin(common::MethodInfo {
3872            id: "gmail.users.drafts.delete",
3873            http_method: hyper::Method::DELETE,
3874        });
3875
3876        for &field in ["userId", "id"].iter() {
3877            if self._additional_params.contains_key(field) {
3878                dlg.finished(false);
3879                return Err(common::Error::FieldClash(field));
3880            }
3881        }
3882
3883        let mut params = Params::with_capacity(3 + self._additional_params.len());
3884        params.push("userId", self._user_id);
3885        params.push("id", self._id);
3886
3887        params.extend(self._additional_params.iter());
3888
3889        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/drafts/{id}";
3890        if self._scopes.is_empty() {
3891            self._scopes.insert(Scope::Gmai.as_ref().to_string());
3892        }
3893
3894        #[allow(clippy::single_element_loop)]
3895        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
3896            url = params.uri_replacement(url, param_name, find_this, false);
3897        }
3898        {
3899            let to_remove = ["id", "userId"];
3900            params.remove_params(&to_remove);
3901        }
3902
3903        let url = params.parse_with_url(&url);
3904
3905        loop {
3906            let token = match self
3907                .hub
3908                .auth
3909                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
3910                .await
3911            {
3912                Ok(token) => token,
3913                Err(e) => match dlg.token(e) {
3914                    Ok(token) => token,
3915                    Err(e) => {
3916                        dlg.finished(false);
3917                        return Err(common::Error::MissingToken(e));
3918                    }
3919                },
3920            };
3921            let mut req_result = {
3922                let client = &self.hub.client;
3923                dlg.pre_request();
3924                let mut req_builder = hyper::Request::builder()
3925                    .method(hyper::Method::DELETE)
3926                    .uri(url.as_str())
3927                    .header(USER_AGENT, self.hub._user_agent.clone());
3928
3929                if let Some(token) = token.as_ref() {
3930                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
3931                }
3932
3933                let request = req_builder
3934                    .header(CONTENT_LENGTH, 0_u64)
3935                    .body(common::to_body::<String>(None));
3936
3937                client.request(request.unwrap()).await
3938            };
3939
3940            match req_result {
3941                Err(err) => {
3942                    if let common::Retry::After(d) = dlg.http_error(&err) {
3943                        sleep(d).await;
3944                        continue;
3945                    }
3946                    dlg.finished(false);
3947                    return Err(common::Error::HttpError(err));
3948                }
3949                Ok(res) => {
3950                    let (mut parts, body) = res.into_parts();
3951                    let mut body = common::Body::new(body);
3952                    if !parts.status.is_success() {
3953                        let bytes = common::to_bytes(body).await.unwrap_or_default();
3954                        let error = serde_json::from_str(&common::to_string(&bytes));
3955                        let response = common::to_response(parts, bytes.into());
3956
3957                        if let common::Retry::After(d) =
3958                            dlg.http_failure(&response, error.as_ref().ok())
3959                        {
3960                            sleep(d).await;
3961                            continue;
3962                        }
3963
3964                        dlg.finished(false);
3965
3966                        return Err(match error {
3967                            Ok(value) => common::Error::BadRequest(value),
3968                            _ => common::Error::Failure(response),
3969                        });
3970                    }
3971                    let response = common::Response::from_parts(parts, body);
3972
3973                    dlg.finished(true);
3974                    return Ok(response);
3975                }
3976            }
3977        }
3978    }
3979
3980    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
3981    ///
3982    /// Sets the *user id* path property to the given value.
3983    ///
3984    /// Even though the property as already been set when instantiating this call,
3985    /// we provide this method for API completeness.
3986    pub fn user_id(mut self, new_value: &str) -> UserDraftDeleteCall<'a, C> {
3987        self._user_id = new_value.to_string();
3988        self
3989    }
3990    /// The ID of the draft to delete.
3991    ///
3992    /// Sets the *id* path property to the given value.
3993    ///
3994    /// Even though the property as already been set when instantiating this call,
3995    /// we provide this method for API completeness.
3996    pub fn id(mut self, new_value: &str) -> UserDraftDeleteCall<'a, C> {
3997        self._id = new_value.to_string();
3998        self
3999    }
4000    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
4001    /// while executing the actual API request.
4002    ///
4003    /// ````text
4004    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
4005    /// ````
4006    ///
4007    /// Sets the *delegate* property to the given value.
4008    pub fn delegate(
4009        mut self,
4010        new_value: &'a mut dyn common::Delegate,
4011    ) -> UserDraftDeleteCall<'a, C> {
4012        self._delegate = Some(new_value);
4013        self
4014    }
4015
4016    /// Set any additional parameter of the query string used in the request.
4017    /// It should be used to set parameters which are not yet available through their own
4018    /// setters.
4019    ///
4020    /// Please note that this method must not be used to set any of the known parameters
4021    /// which have their own setter method. If done anyway, the request will fail.
4022    ///
4023    /// # Additional Parameters
4024    ///
4025    /// * *$.xgafv* (query-string) - V1 error format.
4026    /// * *access_token* (query-string) - OAuth access token.
4027    /// * *alt* (query-string) - Data format for response.
4028    /// * *callback* (query-string) - JSONP
4029    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
4030    /// * *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.
4031    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
4032    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
4033    /// * *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.
4034    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
4035    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
4036    pub fn param<T>(mut self, name: T, value: T) -> UserDraftDeleteCall<'a, C>
4037    where
4038        T: AsRef<str>,
4039    {
4040        self._additional_params
4041            .insert(name.as_ref().to_string(), value.as_ref().to_string());
4042        self
4043    }
4044
4045    /// Identifies the authorization scope for the method you are building.
4046    ///
4047    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
4048    /// [`Scope::Gmai`].
4049    ///
4050    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
4051    /// tokens for more than one scope.
4052    ///
4053    /// Usually there is more than one suitable scope to authorize an operation, some of which may
4054    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
4055    /// sufficient, a read-write scope will do as well.
4056    pub fn add_scope<St>(mut self, scope: St) -> UserDraftDeleteCall<'a, C>
4057    where
4058        St: AsRef<str>,
4059    {
4060        self._scopes.insert(String::from(scope.as_ref()));
4061        self
4062    }
4063    /// Identifies the authorization scope(s) for the method you are building.
4064    ///
4065    /// See [`Self::add_scope()`] for details.
4066    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserDraftDeleteCall<'a, C>
4067    where
4068        I: IntoIterator<Item = St>,
4069        St: AsRef<str>,
4070    {
4071        self._scopes
4072            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
4073        self
4074    }
4075
4076    /// Removes all scopes, and no default scope will be used either.
4077    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
4078    /// for details).
4079    pub fn clear_scopes(mut self) -> UserDraftDeleteCall<'a, C> {
4080        self._scopes.clear();
4081        self
4082    }
4083}
4084
4085/// Gets the specified draft.
4086///
4087/// A builder for the *drafts.get* method supported by a *user* resource.
4088/// It is not used directly, but through a [`UserMethods`] instance.
4089///
4090/// # Example
4091///
4092/// Instantiate a resource method builder
4093///
4094/// ```test_harness,no_run
4095/// # extern crate hyper;
4096/// # extern crate hyper_rustls;
4097/// # extern crate google_gmail1 as gmail1;
4098/// # async fn dox() {
4099/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
4100///
4101/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
4102/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
4103/// #     secret,
4104/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
4105/// # ).build().await.unwrap();
4106///
4107/// # let client = hyper_util::client::legacy::Client::builder(
4108/// #     hyper_util::rt::TokioExecutor::new()
4109/// # )
4110/// # .build(
4111/// #     hyper_rustls::HttpsConnectorBuilder::new()
4112/// #         .with_native_roots()
4113/// #         .unwrap()
4114/// #         .https_or_http()
4115/// #         .enable_http1()
4116/// #         .build()
4117/// # );
4118/// # let mut hub = Gmail::new(client, auth);
4119/// // You can configure optional parameters by calling the respective setters at will, and
4120/// // execute the final call using `doit()`.
4121/// // Values shown here are possibly random and not representative !
4122/// let result = hub.users().drafts_get("userId", "id")
4123///              .format("ipsum")
4124///              .doit().await;
4125/// # }
4126/// ```
4127pub struct UserDraftGetCall<'a, C>
4128where
4129    C: 'a,
4130{
4131    hub: &'a Gmail<C>,
4132    _user_id: String,
4133    _id: String,
4134    _format: Option<String>,
4135    _delegate: Option<&'a mut dyn common::Delegate>,
4136    _additional_params: HashMap<String, String>,
4137    _scopes: BTreeSet<String>,
4138}
4139
4140impl<'a, C> common::CallBuilder for UserDraftGetCall<'a, C> {}
4141
4142impl<'a, C> UserDraftGetCall<'a, C>
4143where
4144    C: common::Connector,
4145{
4146    /// Perform the operation you have build so far.
4147    pub async fn doit(mut self) -> common::Result<(common::Response, Draft)> {
4148        use std::borrow::Cow;
4149        use std::io::{Read, Seek};
4150
4151        use common::{url::Params, ToParts};
4152        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
4153
4154        let mut dd = common::DefaultDelegate;
4155        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
4156        dlg.begin(common::MethodInfo {
4157            id: "gmail.users.drafts.get",
4158            http_method: hyper::Method::GET,
4159        });
4160
4161        for &field in ["alt", "userId", "id", "format"].iter() {
4162            if self._additional_params.contains_key(field) {
4163                dlg.finished(false);
4164                return Err(common::Error::FieldClash(field));
4165            }
4166        }
4167
4168        let mut params = Params::with_capacity(5 + self._additional_params.len());
4169        params.push("userId", self._user_id);
4170        params.push("id", self._id);
4171        if let Some(value) = self._format.as_ref() {
4172            params.push("format", value);
4173        }
4174
4175        params.extend(self._additional_params.iter());
4176
4177        params.push("alt", "json");
4178        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/drafts/{id}";
4179        if self._scopes.is_empty() {
4180            self._scopes.insert(Scope::Readonly.as_ref().to_string());
4181        }
4182
4183        #[allow(clippy::single_element_loop)]
4184        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
4185            url = params.uri_replacement(url, param_name, find_this, false);
4186        }
4187        {
4188            let to_remove = ["id", "userId"];
4189            params.remove_params(&to_remove);
4190        }
4191
4192        let url = params.parse_with_url(&url);
4193
4194        loop {
4195            let token = match self
4196                .hub
4197                .auth
4198                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
4199                .await
4200            {
4201                Ok(token) => token,
4202                Err(e) => match dlg.token(e) {
4203                    Ok(token) => token,
4204                    Err(e) => {
4205                        dlg.finished(false);
4206                        return Err(common::Error::MissingToken(e));
4207                    }
4208                },
4209            };
4210            let mut req_result = {
4211                let client = &self.hub.client;
4212                dlg.pre_request();
4213                let mut req_builder = hyper::Request::builder()
4214                    .method(hyper::Method::GET)
4215                    .uri(url.as_str())
4216                    .header(USER_AGENT, self.hub._user_agent.clone());
4217
4218                if let Some(token) = token.as_ref() {
4219                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
4220                }
4221
4222                let request = req_builder
4223                    .header(CONTENT_LENGTH, 0_u64)
4224                    .body(common::to_body::<String>(None));
4225
4226                client.request(request.unwrap()).await
4227            };
4228
4229            match req_result {
4230                Err(err) => {
4231                    if let common::Retry::After(d) = dlg.http_error(&err) {
4232                        sleep(d).await;
4233                        continue;
4234                    }
4235                    dlg.finished(false);
4236                    return Err(common::Error::HttpError(err));
4237                }
4238                Ok(res) => {
4239                    let (mut parts, body) = res.into_parts();
4240                    let mut body = common::Body::new(body);
4241                    if !parts.status.is_success() {
4242                        let bytes = common::to_bytes(body).await.unwrap_or_default();
4243                        let error = serde_json::from_str(&common::to_string(&bytes));
4244                        let response = common::to_response(parts, bytes.into());
4245
4246                        if let common::Retry::After(d) =
4247                            dlg.http_failure(&response, error.as_ref().ok())
4248                        {
4249                            sleep(d).await;
4250                            continue;
4251                        }
4252
4253                        dlg.finished(false);
4254
4255                        return Err(match error {
4256                            Ok(value) => common::Error::BadRequest(value),
4257                            _ => common::Error::Failure(response),
4258                        });
4259                    }
4260                    let response = {
4261                        let bytes = common::to_bytes(body).await.unwrap_or_default();
4262                        let encoded = common::to_string(&bytes);
4263                        match serde_json::from_str(&encoded) {
4264                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
4265                            Err(error) => {
4266                                dlg.response_json_decode_error(&encoded, &error);
4267                                return Err(common::Error::JsonDecodeError(
4268                                    encoded.to_string(),
4269                                    error,
4270                                ));
4271                            }
4272                        }
4273                    };
4274
4275                    dlg.finished(true);
4276                    return Ok(response);
4277                }
4278            }
4279        }
4280    }
4281
4282    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
4283    ///
4284    /// Sets the *user id* path property to the given value.
4285    ///
4286    /// Even though the property as already been set when instantiating this call,
4287    /// we provide this method for API completeness.
4288    pub fn user_id(mut self, new_value: &str) -> UserDraftGetCall<'a, C> {
4289        self._user_id = new_value.to_string();
4290        self
4291    }
4292    /// The ID of the draft to retrieve.
4293    ///
4294    /// Sets the *id* path property to the given value.
4295    ///
4296    /// Even though the property as already been set when instantiating this call,
4297    /// we provide this method for API completeness.
4298    pub fn id(mut self, new_value: &str) -> UserDraftGetCall<'a, C> {
4299        self._id = new_value.to_string();
4300        self
4301    }
4302    /// The format to return the draft in.
4303    ///
4304    /// Sets the *format* query property to the given value.
4305    pub fn format(mut self, new_value: &str) -> UserDraftGetCall<'a, C> {
4306        self._format = Some(new_value.to_string());
4307        self
4308    }
4309    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
4310    /// while executing the actual API request.
4311    ///
4312    /// ````text
4313    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
4314    /// ````
4315    ///
4316    /// Sets the *delegate* property to the given value.
4317    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> UserDraftGetCall<'a, C> {
4318        self._delegate = Some(new_value);
4319        self
4320    }
4321
4322    /// Set any additional parameter of the query string used in the request.
4323    /// It should be used to set parameters which are not yet available through their own
4324    /// setters.
4325    ///
4326    /// Please note that this method must not be used to set any of the known parameters
4327    /// which have their own setter method. If done anyway, the request will fail.
4328    ///
4329    /// # Additional Parameters
4330    ///
4331    /// * *$.xgafv* (query-string) - V1 error format.
4332    /// * *access_token* (query-string) - OAuth access token.
4333    /// * *alt* (query-string) - Data format for response.
4334    /// * *callback* (query-string) - JSONP
4335    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
4336    /// * *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.
4337    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
4338    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
4339    /// * *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.
4340    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
4341    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
4342    pub fn param<T>(mut self, name: T, value: T) -> UserDraftGetCall<'a, C>
4343    where
4344        T: AsRef<str>,
4345    {
4346        self._additional_params
4347            .insert(name.as_ref().to_string(), value.as_ref().to_string());
4348        self
4349    }
4350
4351    /// Identifies the authorization scope for the method you are building.
4352    ///
4353    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
4354    /// [`Scope::Readonly`].
4355    ///
4356    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
4357    /// tokens for more than one scope.
4358    ///
4359    /// Usually there is more than one suitable scope to authorize an operation, some of which may
4360    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
4361    /// sufficient, a read-write scope will do as well.
4362    pub fn add_scope<St>(mut self, scope: St) -> UserDraftGetCall<'a, C>
4363    where
4364        St: AsRef<str>,
4365    {
4366        self._scopes.insert(String::from(scope.as_ref()));
4367        self
4368    }
4369    /// Identifies the authorization scope(s) for the method you are building.
4370    ///
4371    /// See [`Self::add_scope()`] for details.
4372    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserDraftGetCall<'a, C>
4373    where
4374        I: IntoIterator<Item = St>,
4375        St: AsRef<str>,
4376    {
4377        self._scopes
4378            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
4379        self
4380    }
4381
4382    /// Removes all scopes, and no default scope will be used either.
4383    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
4384    /// for details).
4385    pub fn clear_scopes(mut self) -> UserDraftGetCall<'a, C> {
4386        self._scopes.clear();
4387        self
4388    }
4389}
4390
4391/// Lists the drafts in the user's mailbox.
4392///
4393/// A builder for the *drafts.list* method supported by a *user* resource.
4394/// It is not used directly, but through a [`UserMethods`] instance.
4395///
4396/// # Example
4397///
4398/// Instantiate a resource method builder
4399///
4400/// ```test_harness,no_run
4401/// # extern crate hyper;
4402/// # extern crate hyper_rustls;
4403/// # extern crate google_gmail1 as gmail1;
4404/// # async fn dox() {
4405/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
4406///
4407/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
4408/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
4409/// #     secret,
4410/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
4411/// # ).build().await.unwrap();
4412///
4413/// # let client = hyper_util::client::legacy::Client::builder(
4414/// #     hyper_util::rt::TokioExecutor::new()
4415/// # )
4416/// # .build(
4417/// #     hyper_rustls::HttpsConnectorBuilder::new()
4418/// #         .with_native_roots()
4419/// #         .unwrap()
4420/// #         .https_or_http()
4421/// #         .enable_http1()
4422/// #         .build()
4423/// # );
4424/// # let mut hub = Gmail::new(client, auth);
4425/// // You can configure optional parameters by calling the respective setters at will, and
4426/// // execute the final call using `doit()`.
4427/// // Values shown here are possibly random and not representative !
4428/// let result = hub.users().drafts_list("userId")
4429///              .q("est")
4430///              .page_token("gubergren")
4431///              .max_results(84)
4432///              .include_spam_trash(false)
4433///              .doit().await;
4434/// # }
4435/// ```
4436pub struct UserDraftListCall<'a, C>
4437where
4438    C: 'a,
4439{
4440    hub: &'a Gmail<C>,
4441    _user_id: String,
4442    _q: Option<String>,
4443    _page_token: Option<String>,
4444    _max_results: Option<u32>,
4445    _include_spam_trash: Option<bool>,
4446    _delegate: Option<&'a mut dyn common::Delegate>,
4447    _additional_params: HashMap<String, String>,
4448    _scopes: BTreeSet<String>,
4449}
4450
4451impl<'a, C> common::CallBuilder for UserDraftListCall<'a, C> {}
4452
4453impl<'a, C> UserDraftListCall<'a, C>
4454where
4455    C: common::Connector,
4456{
4457    /// Perform the operation you have build so far.
4458    pub async fn doit(mut self) -> common::Result<(common::Response, ListDraftsResponse)> {
4459        use std::borrow::Cow;
4460        use std::io::{Read, Seek};
4461
4462        use common::{url::Params, ToParts};
4463        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
4464
4465        let mut dd = common::DefaultDelegate;
4466        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
4467        dlg.begin(common::MethodInfo {
4468            id: "gmail.users.drafts.list",
4469            http_method: hyper::Method::GET,
4470        });
4471
4472        for &field in [
4473            "alt",
4474            "userId",
4475            "q",
4476            "pageToken",
4477            "maxResults",
4478            "includeSpamTrash",
4479        ]
4480        .iter()
4481        {
4482            if self._additional_params.contains_key(field) {
4483                dlg.finished(false);
4484                return Err(common::Error::FieldClash(field));
4485            }
4486        }
4487
4488        let mut params = Params::with_capacity(7 + self._additional_params.len());
4489        params.push("userId", self._user_id);
4490        if let Some(value) = self._q.as_ref() {
4491            params.push("q", value);
4492        }
4493        if let Some(value) = self._page_token.as_ref() {
4494            params.push("pageToken", value);
4495        }
4496        if let Some(value) = self._max_results.as_ref() {
4497            params.push("maxResults", value.to_string());
4498        }
4499        if let Some(value) = self._include_spam_trash.as_ref() {
4500            params.push("includeSpamTrash", value.to_string());
4501        }
4502
4503        params.extend(self._additional_params.iter());
4504
4505        params.push("alt", "json");
4506        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/drafts";
4507        if self._scopes.is_empty() {
4508            self._scopes.insert(Scope::Readonly.as_ref().to_string());
4509        }
4510
4511        #[allow(clippy::single_element_loop)]
4512        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
4513            url = params.uri_replacement(url, param_name, find_this, false);
4514        }
4515        {
4516            let to_remove = ["userId"];
4517            params.remove_params(&to_remove);
4518        }
4519
4520        let url = params.parse_with_url(&url);
4521
4522        loop {
4523            let token = match self
4524                .hub
4525                .auth
4526                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
4527                .await
4528            {
4529                Ok(token) => token,
4530                Err(e) => match dlg.token(e) {
4531                    Ok(token) => token,
4532                    Err(e) => {
4533                        dlg.finished(false);
4534                        return Err(common::Error::MissingToken(e));
4535                    }
4536                },
4537            };
4538            let mut req_result = {
4539                let client = &self.hub.client;
4540                dlg.pre_request();
4541                let mut req_builder = hyper::Request::builder()
4542                    .method(hyper::Method::GET)
4543                    .uri(url.as_str())
4544                    .header(USER_AGENT, self.hub._user_agent.clone());
4545
4546                if let Some(token) = token.as_ref() {
4547                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
4548                }
4549
4550                let request = req_builder
4551                    .header(CONTENT_LENGTH, 0_u64)
4552                    .body(common::to_body::<String>(None));
4553
4554                client.request(request.unwrap()).await
4555            };
4556
4557            match req_result {
4558                Err(err) => {
4559                    if let common::Retry::After(d) = dlg.http_error(&err) {
4560                        sleep(d).await;
4561                        continue;
4562                    }
4563                    dlg.finished(false);
4564                    return Err(common::Error::HttpError(err));
4565                }
4566                Ok(res) => {
4567                    let (mut parts, body) = res.into_parts();
4568                    let mut body = common::Body::new(body);
4569                    if !parts.status.is_success() {
4570                        let bytes = common::to_bytes(body).await.unwrap_or_default();
4571                        let error = serde_json::from_str(&common::to_string(&bytes));
4572                        let response = common::to_response(parts, bytes.into());
4573
4574                        if let common::Retry::After(d) =
4575                            dlg.http_failure(&response, error.as_ref().ok())
4576                        {
4577                            sleep(d).await;
4578                            continue;
4579                        }
4580
4581                        dlg.finished(false);
4582
4583                        return Err(match error {
4584                            Ok(value) => common::Error::BadRequest(value),
4585                            _ => common::Error::Failure(response),
4586                        });
4587                    }
4588                    let response = {
4589                        let bytes = common::to_bytes(body).await.unwrap_or_default();
4590                        let encoded = common::to_string(&bytes);
4591                        match serde_json::from_str(&encoded) {
4592                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
4593                            Err(error) => {
4594                                dlg.response_json_decode_error(&encoded, &error);
4595                                return Err(common::Error::JsonDecodeError(
4596                                    encoded.to_string(),
4597                                    error,
4598                                ));
4599                            }
4600                        }
4601                    };
4602
4603                    dlg.finished(true);
4604                    return Ok(response);
4605                }
4606            }
4607        }
4608    }
4609
4610    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
4611    ///
4612    /// Sets the *user id* path property to the given value.
4613    ///
4614    /// Even though the property as already been set when instantiating this call,
4615    /// we provide this method for API completeness.
4616    pub fn user_id(mut self, new_value: &str) -> UserDraftListCall<'a, C> {
4617        self._user_id = new_value.to_string();
4618        self
4619    }
4620    /// Only return draft messages matching the specified query. Supports the same query format as the Gmail search box. For example, `"from:someuser@example.com rfc822msgid: is:unread"`.
4621    ///
4622    /// Sets the *q* query property to the given value.
4623    pub fn q(mut self, new_value: &str) -> UserDraftListCall<'a, C> {
4624        self._q = Some(new_value.to_string());
4625        self
4626    }
4627    /// Page token to retrieve a specific page of results in the list.
4628    ///
4629    /// Sets the *page token* query property to the given value.
4630    pub fn page_token(mut self, new_value: &str) -> UserDraftListCall<'a, C> {
4631        self._page_token = Some(new_value.to_string());
4632        self
4633    }
4634    /// Maximum number of drafts to return. This field defaults to 100. The maximum allowed value for this field is 500.
4635    ///
4636    /// Sets the *max results* query property to the given value.
4637    pub fn max_results(mut self, new_value: u32) -> UserDraftListCall<'a, C> {
4638        self._max_results = Some(new_value);
4639        self
4640    }
4641    /// Include drafts from `SPAM` and `TRASH` in the results.
4642    ///
4643    /// Sets the *include spam trash* query property to the given value.
4644    pub fn include_spam_trash(mut self, new_value: bool) -> UserDraftListCall<'a, C> {
4645        self._include_spam_trash = Some(new_value);
4646        self
4647    }
4648    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
4649    /// while executing the actual API request.
4650    ///
4651    /// ````text
4652    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
4653    /// ````
4654    ///
4655    /// Sets the *delegate* property to the given value.
4656    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> UserDraftListCall<'a, C> {
4657        self._delegate = Some(new_value);
4658        self
4659    }
4660
4661    /// Set any additional parameter of the query string used in the request.
4662    /// It should be used to set parameters which are not yet available through their own
4663    /// setters.
4664    ///
4665    /// Please note that this method must not be used to set any of the known parameters
4666    /// which have their own setter method. If done anyway, the request will fail.
4667    ///
4668    /// # Additional Parameters
4669    ///
4670    /// * *$.xgafv* (query-string) - V1 error format.
4671    /// * *access_token* (query-string) - OAuth access token.
4672    /// * *alt* (query-string) - Data format for response.
4673    /// * *callback* (query-string) - JSONP
4674    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
4675    /// * *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.
4676    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
4677    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
4678    /// * *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.
4679    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
4680    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
4681    pub fn param<T>(mut self, name: T, value: T) -> UserDraftListCall<'a, C>
4682    where
4683        T: AsRef<str>,
4684    {
4685        self._additional_params
4686            .insert(name.as_ref().to_string(), value.as_ref().to_string());
4687        self
4688    }
4689
4690    /// Identifies the authorization scope for the method you are building.
4691    ///
4692    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
4693    /// [`Scope::Readonly`].
4694    ///
4695    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
4696    /// tokens for more than one scope.
4697    ///
4698    /// Usually there is more than one suitable scope to authorize an operation, some of which may
4699    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
4700    /// sufficient, a read-write scope will do as well.
4701    pub fn add_scope<St>(mut self, scope: St) -> UserDraftListCall<'a, C>
4702    where
4703        St: AsRef<str>,
4704    {
4705        self._scopes.insert(String::from(scope.as_ref()));
4706        self
4707    }
4708    /// Identifies the authorization scope(s) for the method you are building.
4709    ///
4710    /// See [`Self::add_scope()`] for details.
4711    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserDraftListCall<'a, C>
4712    where
4713        I: IntoIterator<Item = St>,
4714        St: AsRef<str>,
4715    {
4716        self._scopes
4717            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
4718        self
4719    }
4720
4721    /// Removes all scopes, and no default scope will be used either.
4722    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
4723    /// for details).
4724    pub fn clear_scopes(mut self) -> UserDraftListCall<'a, C> {
4725        self._scopes.clear();
4726        self
4727    }
4728}
4729
4730/// Sends the specified, existing draft to the recipients in the `To`, `Cc`, and `Bcc` headers.
4731///
4732/// A builder for the *drafts.send* method supported by a *user* resource.
4733/// It is not used directly, but through a [`UserMethods`] instance.
4734///
4735/// # Example
4736///
4737/// Instantiate a resource method builder
4738///
4739/// ```test_harness,no_run
4740/// # extern crate hyper;
4741/// # extern crate hyper_rustls;
4742/// # extern crate google_gmail1 as gmail1;
4743/// use gmail1::api::Draft;
4744/// use std::fs;
4745/// # async fn dox() {
4746/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
4747///
4748/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
4749/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
4750/// #     secret,
4751/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
4752/// # ).build().await.unwrap();
4753///
4754/// # let client = hyper_util::client::legacy::Client::builder(
4755/// #     hyper_util::rt::TokioExecutor::new()
4756/// # )
4757/// # .build(
4758/// #     hyper_rustls::HttpsConnectorBuilder::new()
4759/// #         .with_native_roots()
4760/// #         .unwrap()
4761/// #         .https_or_http()
4762/// #         .enable_http1()
4763/// #         .build()
4764/// # );
4765/// # let mut hub = Gmail::new(client, auth);
4766/// // As the method needs a request, you would usually fill it with the desired information
4767/// // into the respective structure. Some of the parts shown here might not be applicable !
4768/// // Values shown here are possibly random and not representative !
4769/// let mut req = Draft::default();
4770///
4771/// // You can configure optional parameters by calling the respective setters at will, and
4772/// // execute the final call using `upload_resumable(...)`.
4773/// // Values shown here are possibly random and not representative !
4774/// let result = hub.users().drafts_send(req, "userId")
4775///              .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()).await;
4776/// # }
4777/// ```
4778pub struct UserDraftSendCall<'a, C>
4779where
4780    C: 'a,
4781{
4782    hub: &'a Gmail<C>,
4783    _request: Draft,
4784    _user_id: String,
4785    _delegate: Option<&'a mut dyn common::Delegate>,
4786    _additional_params: HashMap<String, String>,
4787    _scopes: BTreeSet<String>,
4788}
4789
4790impl<'a, C> common::CallBuilder for UserDraftSendCall<'a, C> {}
4791
4792impl<'a, C> UserDraftSendCall<'a, C>
4793where
4794    C: common::Connector,
4795{
4796    /// Perform the operation you have build so far.
4797    async fn doit<RS>(
4798        mut self,
4799        mut reader: RS,
4800        reader_mime_type: mime::Mime,
4801        protocol: common::UploadProtocol,
4802    ) -> common::Result<(common::Response, Message)>
4803    where
4804        RS: common::ReadSeek,
4805    {
4806        use std::borrow::Cow;
4807        use std::io::{Read, Seek};
4808
4809        use common::{url::Params, ToParts};
4810        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
4811
4812        let mut dd = common::DefaultDelegate;
4813        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
4814        dlg.begin(common::MethodInfo {
4815            id: "gmail.users.drafts.send",
4816            http_method: hyper::Method::POST,
4817        });
4818
4819        for &field in ["alt", "userId"].iter() {
4820            if self._additional_params.contains_key(field) {
4821                dlg.finished(false);
4822                return Err(common::Error::FieldClash(field));
4823            }
4824        }
4825
4826        let mut params = Params::with_capacity(4 + self._additional_params.len());
4827        params.push("userId", self._user_id);
4828
4829        params.extend(self._additional_params.iter());
4830
4831        params.push("alt", "json");
4832        let (mut url, upload_type) = if protocol == common::UploadProtocol::Resumable {
4833            (
4834                self.hub._root_url.clone() + "resumable/upload/gmail/v1/users/{userId}/drafts/send",
4835                "resumable",
4836            )
4837        } else if protocol == common::UploadProtocol::Simple {
4838            (
4839                self.hub._root_url.clone() + "upload/gmail/v1/users/{userId}/drafts/send",
4840                "multipart",
4841            )
4842        } else {
4843            unreachable!()
4844        };
4845        params.push("uploadType", upload_type);
4846        if self._scopes.is_empty() {
4847            self._scopes.insert(Scope::Gmai.as_ref().to_string());
4848        }
4849
4850        #[allow(clippy::single_element_loop)]
4851        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
4852            url = params.uri_replacement(url, param_name, find_this, false);
4853        }
4854        {
4855            let to_remove = ["userId"];
4856            params.remove_params(&to_remove);
4857        }
4858
4859        let url = params.parse_with_url(&url);
4860
4861        let mut json_mime_type = mime::APPLICATION_JSON;
4862        let mut request_value_reader = {
4863            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
4864            common::remove_json_null_values(&mut value);
4865            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
4866            serde_json::to_writer(&mut dst, &value).unwrap();
4867            dst
4868        };
4869        let request_size = request_value_reader
4870            .seek(std::io::SeekFrom::End(0))
4871            .unwrap();
4872        request_value_reader
4873            .seek(std::io::SeekFrom::Start(0))
4874            .unwrap();
4875
4876        let mut upload_url_from_server;
4877
4878        loop {
4879            let token = match self
4880                .hub
4881                .auth
4882                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
4883                .await
4884            {
4885                Ok(token) => token,
4886                Err(e) => match dlg.token(e) {
4887                    Ok(token) => token,
4888                    Err(e) => {
4889                        dlg.finished(false);
4890                        return Err(common::Error::MissingToken(e));
4891                    }
4892                },
4893            };
4894            request_value_reader
4895                .seek(std::io::SeekFrom::Start(0))
4896                .unwrap();
4897            let mut req_result = {
4898                let mut mp_reader: common::MultiPartReader = Default::default();
4899                let (mut body_reader, content_type) = match protocol {
4900                    common::UploadProtocol::Simple => {
4901                        mp_reader.reserve_exact(2);
4902                        let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
4903                        reader.seek(std::io::SeekFrom::Start(0)).unwrap();
4904                        if size > 36700160 {
4905                            return Err(common::Error::UploadSizeLimitExceeded(size, 36700160));
4906                        }
4907                        mp_reader
4908                            .add_part(
4909                                &mut request_value_reader,
4910                                request_size,
4911                                json_mime_type.clone(),
4912                            )
4913                            .add_part(&mut reader, size, reader_mime_type.clone());
4914                        (
4915                            &mut mp_reader as &mut (dyn std::io::Read + Send),
4916                            common::MultiPartReader::mime_type(),
4917                        )
4918                    }
4919                    _ => (
4920                        &mut request_value_reader as &mut (dyn std::io::Read + Send),
4921                        json_mime_type.clone(),
4922                    ),
4923                };
4924                let client = &self.hub.client;
4925                dlg.pre_request();
4926                let mut req_builder = hyper::Request::builder()
4927                    .method(hyper::Method::POST)
4928                    .uri(url.as_str())
4929                    .header(USER_AGENT, self.hub._user_agent.clone());
4930
4931                if let Some(token) = token.as_ref() {
4932                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
4933                }
4934
4935                upload_url_from_server = true;
4936                if protocol == common::UploadProtocol::Resumable {
4937                    req_builder = req_builder
4938                        .header("X-Upload-Content-Type", format!("{}", reader_mime_type));
4939                }
4940
4941                let mut body_reader_bytes = vec![];
4942                body_reader.read_to_end(&mut body_reader_bytes).unwrap();
4943                let request = req_builder
4944                    .header(CONTENT_TYPE, content_type.to_string())
4945                    .body(common::to_body(body_reader_bytes.into()));
4946
4947                client.request(request.unwrap()).await
4948            };
4949
4950            match req_result {
4951                Err(err) => {
4952                    if let common::Retry::After(d) = dlg.http_error(&err) {
4953                        sleep(d).await;
4954                        continue;
4955                    }
4956                    dlg.finished(false);
4957                    return Err(common::Error::HttpError(err));
4958                }
4959                Ok(res) => {
4960                    let (mut parts, body) = res.into_parts();
4961                    let mut body = common::Body::new(body);
4962                    if !parts.status.is_success() {
4963                        let bytes = common::to_bytes(body).await.unwrap_or_default();
4964                        let error = serde_json::from_str(&common::to_string(&bytes));
4965                        let response = common::to_response(parts, bytes.into());
4966
4967                        if let common::Retry::After(d) =
4968                            dlg.http_failure(&response, error.as_ref().ok())
4969                        {
4970                            sleep(d).await;
4971                            continue;
4972                        }
4973
4974                        dlg.finished(false);
4975
4976                        return Err(match error {
4977                            Ok(value) => common::Error::BadRequest(value),
4978                            _ => common::Error::Failure(response),
4979                        });
4980                    }
4981                    if protocol == common::UploadProtocol::Resumable {
4982                        let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
4983                        reader.seek(std::io::SeekFrom::Start(0)).unwrap();
4984                        if size > 36700160 {
4985                            return Err(common::Error::UploadSizeLimitExceeded(size, 36700160));
4986                        }
4987                        let upload_result = {
4988                            let url_str = &parts
4989                                .headers
4990                                .get("Location")
4991                                .expect("LOCATION header is part of protocol")
4992                                .to_str()
4993                                .unwrap();
4994                            if upload_url_from_server {
4995                                dlg.store_upload_url(Some(url_str));
4996                            }
4997
4998                            common::ResumableUploadHelper {
4999                                client: &self.hub.client,
5000                                delegate: dlg,
5001                                start_at: if upload_url_from_server {
5002                                    Some(0)
5003                                } else {
5004                                    None
5005                                },
5006                                auth: &self.hub.auth,
5007                                user_agent: &self.hub._user_agent,
5008                                // TODO: Check this assumption
5009                                auth_header: format!(
5010                                    "Bearer {}",
5011                                    token
5012                                        .ok_or_else(|| common::Error::MissingToken(
5013                                            "resumable upload requires token".into()
5014                                        ))?
5015                                        .as_str()
5016                                ),
5017                                url: url_str,
5018                                reader: &mut reader,
5019                                media_type: reader_mime_type.clone(),
5020                                content_length: size,
5021                            }
5022                            .upload()
5023                            .await
5024                        };
5025                        match upload_result {
5026                            None => {
5027                                dlg.finished(false);
5028                                return Err(common::Error::Cancelled);
5029                            }
5030                            Some(Err(err)) => {
5031                                dlg.finished(false);
5032                                return Err(common::Error::HttpError(err));
5033                            }
5034                            Some(Ok(response)) => {
5035                                (parts, body) = response.into_parts();
5036                                if !parts.status.is_success() {
5037                                    dlg.store_upload_url(None);
5038                                    dlg.finished(false);
5039                                    return Err(common::Error::Failure(
5040                                        common::Response::from_parts(parts, body),
5041                                    ));
5042                                }
5043                            }
5044                        }
5045                    }
5046                    let response = {
5047                        let bytes = common::to_bytes(body).await.unwrap_or_default();
5048                        let encoded = common::to_string(&bytes);
5049                        match serde_json::from_str(&encoded) {
5050                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
5051                            Err(error) => {
5052                                dlg.response_json_decode_error(&encoded, &error);
5053                                return Err(common::Error::JsonDecodeError(
5054                                    encoded.to_string(),
5055                                    error,
5056                                ));
5057                            }
5058                        }
5059                    };
5060
5061                    dlg.finished(true);
5062                    return Ok(response);
5063                }
5064            }
5065        }
5066    }
5067
5068    /// Upload media in a resumable fashion.
5069    /// Even if the upload fails or is interrupted, it can be resumed for a
5070    /// certain amount of time as the server maintains state temporarily.
5071    ///
5072    /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL
5073    /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate
5074    /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using
5075    /// `cancel_chunk_upload(...)`.
5076    ///
5077    /// * *multipart*: yes
5078    /// * *max size*: 36700160
5079    /// * *valid mime types*: 'message/*'
5080    pub async fn upload_resumable<RS>(
5081        self,
5082        resumeable_stream: RS,
5083        mime_type: mime::Mime,
5084    ) -> common::Result<(common::Response, Message)>
5085    where
5086        RS: common::ReadSeek,
5087    {
5088        self.doit(
5089            resumeable_stream,
5090            mime_type,
5091            common::UploadProtocol::Resumable,
5092        )
5093        .await
5094    }
5095    /// Upload media all at once.
5096    /// If the upload fails for whichever reason, all progress is lost.
5097    ///
5098    /// * *multipart*: yes
5099    /// * *max size*: 36700160
5100    /// * *valid mime types*: 'message/*'
5101    pub async fn upload<RS>(
5102        self,
5103        stream: RS,
5104        mime_type: mime::Mime,
5105    ) -> common::Result<(common::Response, Message)>
5106    where
5107        RS: common::ReadSeek,
5108    {
5109        self.doit(stream, mime_type, common::UploadProtocol::Simple)
5110            .await
5111    }
5112
5113    ///
5114    /// Sets the *request* property to the given value.
5115    ///
5116    /// Even though the property as already been set when instantiating this call,
5117    /// we provide this method for API completeness.
5118    pub fn request(mut self, new_value: Draft) -> UserDraftSendCall<'a, C> {
5119        self._request = new_value;
5120        self
5121    }
5122    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
5123    ///
5124    /// Sets the *user id* path property to the given value.
5125    ///
5126    /// Even though the property as already been set when instantiating this call,
5127    /// we provide this method for API completeness.
5128    pub fn user_id(mut self, new_value: &str) -> UserDraftSendCall<'a, C> {
5129        self._user_id = new_value.to_string();
5130        self
5131    }
5132    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
5133    /// while executing the actual API request.
5134    ///
5135    /// ````text
5136    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
5137    /// ````
5138    ///
5139    /// Sets the *delegate* property to the given value.
5140    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> UserDraftSendCall<'a, C> {
5141        self._delegate = Some(new_value);
5142        self
5143    }
5144
5145    /// Set any additional parameter of the query string used in the request.
5146    /// It should be used to set parameters which are not yet available through their own
5147    /// setters.
5148    ///
5149    /// Please note that this method must not be used to set any of the known parameters
5150    /// which have their own setter method. If done anyway, the request will fail.
5151    ///
5152    /// # Additional Parameters
5153    ///
5154    /// * *$.xgafv* (query-string) - V1 error format.
5155    /// * *access_token* (query-string) - OAuth access token.
5156    /// * *alt* (query-string) - Data format for response.
5157    /// * *callback* (query-string) - JSONP
5158    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
5159    /// * *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.
5160    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
5161    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
5162    /// * *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.
5163    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
5164    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
5165    pub fn param<T>(mut self, name: T, value: T) -> UserDraftSendCall<'a, C>
5166    where
5167        T: AsRef<str>,
5168    {
5169        self._additional_params
5170            .insert(name.as_ref().to_string(), value.as_ref().to_string());
5171        self
5172    }
5173
5174    /// Identifies the authorization scope for the method you are building.
5175    ///
5176    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
5177    /// [`Scope::Gmai`].
5178    ///
5179    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
5180    /// tokens for more than one scope.
5181    ///
5182    /// Usually there is more than one suitable scope to authorize an operation, some of which may
5183    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
5184    /// sufficient, a read-write scope will do as well.
5185    pub fn add_scope<St>(mut self, scope: St) -> UserDraftSendCall<'a, C>
5186    where
5187        St: AsRef<str>,
5188    {
5189        self._scopes.insert(String::from(scope.as_ref()));
5190        self
5191    }
5192    /// Identifies the authorization scope(s) for the method you are building.
5193    ///
5194    /// See [`Self::add_scope()`] for details.
5195    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserDraftSendCall<'a, C>
5196    where
5197        I: IntoIterator<Item = St>,
5198        St: AsRef<str>,
5199    {
5200        self._scopes
5201            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
5202        self
5203    }
5204
5205    /// Removes all scopes, and no default scope will be used either.
5206    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
5207    /// for details).
5208    pub fn clear_scopes(mut self) -> UserDraftSendCall<'a, C> {
5209        self._scopes.clear();
5210        self
5211    }
5212}
5213
5214/// Replaces a draft's content.
5215///
5216/// A builder for the *drafts.update* method supported by a *user* resource.
5217/// It is not used directly, but through a [`UserMethods`] instance.
5218///
5219/// # Example
5220///
5221/// Instantiate a resource method builder
5222///
5223/// ```test_harness,no_run
5224/// # extern crate hyper;
5225/// # extern crate hyper_rustls;
5226/// # extern crate google_gmail1 as gmail1;
5227/// use gmail1::api::Draft;
5228/// use std::fs;
5229/// # async fn dox() {
5230/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
5231///
5232/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
5233/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
5234/// #     secret,
5235/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
5236/// # ).build().await.unwrap();
5237///
5238/// # let client = hyper_util::client::legacy::Client::builder(
5239/// #     hyper_util::rt::TokioExecutor::new()
5240/// # )
5241/// # .build(
5242/// #     hyper_rustls::HttpsConnectorBuilder::new()
5243/// #         .with_native_roots()
5244/// #         .unwrap()
5245/// #         .https_or_http()
5246/// #         .enable_http1()
5247/// #         .build()
5248/// # );
5249/// # let mut hub = Gmail::new(client, auth);
5250/// // As the method needs a request, you would usually fill it with the desired information
5251/// // into the respective structure. Some of the parts shown here might not be applicable !
5252/// // Values shown here are possibly random and not representative !
5253/// let mut req = Draft::default();
5254///
5255/// // You can configure optional parameters by calling the respective setters at will, and
5256/// // execute the final call using `upload_resumable(...)`.
5257/// // Values shown here are possibly random and not representative !
5258/// let result = hub.users().drafts_update(req, "userId", "id")
5259///              .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()).await;
5260/// # }
5261/// ```
5262pub struct UserDraftUpdateCall<'a, C>
5263where
5264    C: 'a,
5265{
5266    hub: &'a Gmail<C>,
5267    _request: Draft,
5268    _user_id: String,
5269    _id: String,
5270    _delegate: Option<&'a mut dyn common::Delegate>,
5271    _additional_params: HashMap<String, String>,
5272    _scopes: BTreeSet<String>,
5273}
5274
5275impl<'a, C> common::CallBuilder for UserDraftUpdateCall<'a, C> {}
5276
5277impl<'a, C> UserDraftUpdateCall<'a, C>
5278where
5279    C: common::Connector,
5280{
5281    /// Perform the operation you have build so far.
5282    async fn doit<RS>(
5283        mut self,
5284        mut reader: RS,
5285        reader_mime_type: mime::Mime,
5286        protocol: common::UploadProtocol,
5287    ) -> common::Result<(common::Response, Draft)>
5288    where
5289        RS: common::ReadSeek,
5290    {
5291        use std::borrow::Cow;
5292        use std::io::{Read, Seek};
5293
5294        use common::{url::Params, ToParts};
5295        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
5296
5297        let mut dd = common::DefaultDelegate;
5298        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
5299        dlg.begin(common::MethodInfo {
5300            id: "gmail.users.drafts.update",
5301            http_method: hyper::Method::PUT,
5302        });
5303
5304        for &field in ["alt", "userId", "id"].iter() {
5305            if self._additional_params.contains_key(field) {
5306                dlg.finished(false);
5307                return Err(common::Error::FieldClash(field));
5308            }
5309        }
5310
5311        let mut params = Params::with_capacity(5 + self._additional_params.len());
5312        params.push("userId", self._user_id);
5313        params.push("id", self._id);
5314
5315        params.extend(self._additional_params.iter());
5316
5317        params.push("alt", "json");
5318        let (mut url, upload_type) = if protocol == common::UploadProtocol::Resumable {
5319            (
5320                self.hub._root_url.clone() + "resumable/upload/gmail/v1/users/{userId}/drafts/{id}",
5321                "resumable",
5322            )
5323        } else if protocol == common::UploadProtocol::Simple {
5324            (
5325                self.hub._root_url.clone() + "upload/gmail/v1/users/{userId}/drafts/{id}",
5326                "multipart",
5327            )
5328        } else {
5329            unreachable!()
5330        };
5331        params.push("uploadType", upload_type);
5332        if self._scopes.is_empty() {
5333            self._scopes.insert(Scope::Gmai.as_ref().to_string());
5334        }
5335
5336        #[allow(clippy::single_element_loop)]
5337        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
5338            url = params.uri_replacement(url, param_name, find_this, false);
5339        }
5340        {
5341            let to_remove = ["id", "userId"];
5342            params.remove_params(&to_remove);
5343        }
5344
5345        let url = params.parse_with_url(&url);
5346
5347        let mut json_mime_type = mime::APPLICATION_JSON;
5348        let mut request_value_reader = {
5349            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
5350            common::remove_json_null_values(&mut value);
5351            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
5352            serde_json::to_writer(&mut dst, &value).unwrap();
5353            dst
5354        };
5355        let request_size = request_value_reader
5356            .seek(std::io::SeekFrom::End(0))
5357            .unwrap();
5358        request_value_reader
5359            .seek(std::io::SeekFrom::Start(0))
5360            .unwrap();
5361
5362        let mut upload_url_from_server;
5363
5364        loop {
5365            let token = match self
5366                .hub
5367                .auth
5368                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
5369                .await
5370            {
5371                Ok(token) => token,
5372                Err(e) => match dlg.token(e) {
5373                    Ok(token) => token,
5374                    Err(e) => {
5375                        dlg.finished(false);
5376                        return Err(common::Error::MissingToken(e));
5377                    }
5378                },
5379            };
5380            request_value_reader
5381                .seek(std::io::SeekFrom::Start(0))
5382                .unwrap();
5383            let mut req_result = {
5384                let mut mp_reader: common::MultiPartReader = Default::default();
5385                let (mut body_reader, content_type) = match protocol {
5386                    common::UploadProtocol::Simple => {
5387                        mp_reader.reserve_exact(2);
5388                        let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
5389                        reader.seek(std::io::SeekFrom::Start(0)).unwrap();
5390                        if size > 36700160 {
5391                            return Err(common::Error::UploadSizeLimitExceeded(size, 36700160));
5392                        }
5393                        mp_reader
5394                            .add_part(
5395                                &mut request_value_reader,
5396                                request_size,
5397                                json_mime_type.clone(),
5398                            )
5399                            .add_part(&mut reader, size, reader_mime_type.clone());
5400                        (
5401                            &mut mp_reader as &mut (dyn std::io::Read + Send),
5402                            common::MultiPartReader::mime_type(),
5403                        )
5404                    }
5405                    _ => (
5406                        &mut request_value_reader as &mut (dyn std::io::Read + Send),
5407                        json_mime_type.clone(),
5408                    ),
5409                };
5410                let client = &self.hub.client;
5411                dlg.pre_request();
5412                let mut req_builder = hyper::Request::builder()
5413                    .method(hyper::Method::PUT)
5414                    .uri(url.as_str())
5415                    .header(USER_AGENT, self.hub._user_agent.clone());
5416
5417                if let Some(token) = token.as_ref() {
5418                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
5419                }
5420
5421                upload_url_from_server = true;
5422                if protocol == common::UploadProtocol::Resumable {
5423                    req_builder = req_builder
5424                        .header("X-Upload-Content-Type", format!("{}", reader_mime_type));
5425                }
5426
5427                let mut body_reader_bytes = vec![];
5428                body_reader.read_to_end(&mut body_reader_bytes).unwrap();
5429                let request = req_builder
5430                    .header(CONTENT_TYPE, content_type.to_string())
5431                    .body(common::to_body(body_reader_bytes.into()));
5432
5433                client.request(request.unwrap()).await
5434            };
5435
5436            match req_result {
5437                Err(err) => {
5438                    if let common::Retry::After(d) = dlg.http_error(&err) {
5439                        sleep(d).await;
5440                        continue;
5441                    }
5442                    dlg.finished(false);
5443                    return Err(common::Error::HttpError(err));
5444                }
5445                Ok(res) => {
5446                    let (mut parts, body) = res.into_parts();
5447                    let mut body = common::Body::new(body);
5448                    if !parts.status.is_success() {
5449                        let bytes = common::to_bytes(body).await.unwrap_or_default();
5450                        let error = serde_json::from_str(&common::to_string(&bytes));
5451                        let response = common::to_response(parts, bytes.into());
5452
5453                        if let common::Retry::After(d) =
5454                            dlg.http_failure(&response, error.as_ref().ok())
5455                        {
5456                            sleep(d).await;
5457                            continue;
5458                        }
5459
5460                        dlg.finished(false);
5461
5462                        return Err(match error {
5463                            Ok(value) => common::Error::BadRequest(value),
5464                            _ => common::Error::Failure(response),
5465                        });
5466                    }
5467                    if protocol == common::UploadProtocol::Resumable {
5468                        let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
5469                        reader.seek(std::io::SeekFrom::Start(0)).unwrap();
5470                        if size > 36700160 {
5471                            return Err(common::Error::UploadSizeLimitExceeded(size, 36700160));
5472                        }
5473                        let upload_result = {
5474                            let url_str = &parts
5475                                .headers
5476                                .get("Location")
5477                                .expect("LOCATION header is part of protocol")
5478                                .to_str()
5479                                .unwrap();
5480                            if upload_url_from_server {
5481                                dlg.store_upload_url(Some(url_str));
5482                            }
5483
5484                            common::ResumableUploadHelper {
5485                                client: &self.hub.client,
5486                                delegate: dlg,
5487                                start_at: if upload_url_from_server {
5488                                    Some(0)
5489                                } else {
5490                                    None
5491                                },
5492                                auth: &self.hub.auth,
5493                                user_agent: &self.hub._user_agent,
5494                                // TODO: Check this assumption
5495                                auth_header: format!(
5496                                    "Bearer {}",
5497                                    token
5498                                        .ok_or_else(|| common::Error::MissingToken(
5499                                            "resumable upload requires token".into()
5500                                        ))?
5501                                        .as_str()
5502                                ),
5503                                url: url_str,
5504                                reader: &mut reader,
5505                                media_type: reader_mime_type.clone(),
5506                                content_length: size,
5507                            }
5508                            .upload()
5509                            .await
5510                        };
5511                        match upload_result {
5512                            None => {
5513                                dlg.finished(false);
5514                                return Err(common::Error::Cancelled);
5515                            }
5516                            Some(Err(err)) => {
5517                                dlg.finished(false);
5518                                return Err(common::Error::HttpError(err));
5519                            }
5520                            Some(Ok(response)) => {
5521                                (parts, body) = response.into_parts();
5522                                if !parts.status.is_success() {
5523                                    dlg.store_upload_url(None);
5524                                    dlg.finished(false);
5525                                    return Err(common::Error::Failure(
5526                                        common::Response::from_parts(parts, body),
5527                                    ));
5528                                }
5529                            }
5530                        }
5531                    }
5532                    let response = {
5533                        let bytes = common::to_bytes(body).await.unwrap_or_default();
5534                        let encoded = common::to_string(&bytes);
5535                        match serde_json::from_str(&encoded) {
5536                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
5537                            Err(error) => {
5538                                dlg.response_json_decode_error(&encoded, &error);
5539                                return Err(common::Error::JsonDecodeError(
5540                                    encoded.to_string(),
5541                                    error,
5542                                ));
5543                            }
5544                        }
5545                    };
5546
5547                    dlg.finished(true);
5548                    return Ok(response);
5549                }
5550            }
5551        }
5552    }
5553
5554    /// Upload media in a resumable fashion.
5555    /// Even if the upload fails or is interrupted, it can be resumed for a
5556    /// certain amount of time as the server maintains state temporarily.
5557    ///
5558    /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL
5559    /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate
5560    /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using
5561    /// `cancel_chunk_upload(...)`.
5562    ///
5563    /// * *multipart*: yes
5564    /// * *max size*: 36700160
5565    /// * *valid mime types*: 'message/*'
5566    pub async fn upload_resumable<RS>(
5567        self,
5568        resumeable_stream: RS,
5569        mime_type: mime::Mime,
5570    ) -> common::Result<(common::Response, Draft)>
5571    where
5572        RS: common::ReadSeek,
5573    {
5574        self.doit(
5575            resumeable_stream,
5576            mime_type,
5577            common::UploadProtocol::Resumable,
5578        )
5579        .await
5580    }
5581    /// Upload media all at once.
5582    /// If the upload fails for whichever reason, all progress is lost.
5583    ///
5584    /// * *multipart*: yes
5585    /// * *max size*: 36700160
5586    /// * *valid mime types*: 'message/*'
5587    pub async fn upload<RS>(
5588        self,
5589        stream: RS,
5590        mime_type: mime::Mime,
5591    ) -> common::Result<(common::Response, Draft)>
5592    where
5593        RS: common::ReadSeek,
5594    {
5595        self.doit(stream, mime_type, common::UploadProtocol::Simple)
5596            .await
5597    }
5598
5599    ///
5600    /// Sets the *request* property to the given value.
5601    ///
5602    /// Even though the property as already been set when instantiating this call,
5603    /// we provide this method for API completeness.
5604    pub fn request(mut self, new_value: Draft) -> UserDraftUpdateCall<'a, C> {
5605        self._request = new_value;
5606        self
5607    }
5608    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
5609    ///
5610    /// Sets the *user id* path property to the given value.
5611    ///
5612    /// Even though the property as already been set when instantiating this call,
5613    /// we provide this method for API completeness.
5614    pub fn user_id(mut self, new_value: &str) -> UserDraftUpdateCall<'a, C> {
5615        self._user_id = new_value.to_string();
5616        self
5617    }
5618    /// The ID of the draft to update.
5619    ///
5620    /// Sets the *id* path property to the given value.
5621    ///
5622    /// Even though the property as already been set when instantiating this call,
5623    /// we provide this method for API completeness.
5624    pub fn id(mut self, new_value: &str) -> UserDraftUpdateCall<'a, C> {
5625        self._id = new_value.to_string();
5626        self
5627    }
5628    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
5629    /// while executing the actual API request.
5630    ///
5631    /// ````text
5632    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
5633    /// ````
5634    ///
5635    /// Sets the *delegate* property to the given value.
5636    pub fn delegate(
5637        mut self,
5638        new_value: &'a mut dyn common::Delegate,
5639    ) -> UserDraftUpdateCall<'a, C> {
5640        self._delegate = Some(new_value);
5641        self
5642    }
5643
5644    /// Set any additional parameter of the query string used in the request.
5645    /// It should be used to set parameters which are not yet available through their own
5646    /// setters.
5647    ///
5648    /// Please note that this method must not be used to set any of the known parameters
5649    /// which have their own setter method. If done anyway, the request will fail.
5650    ///
5651    /// # Additional Parameters
5652    ///
5653    /// * *$.xgafv* (query-string) - V1 error format.
5654    /// * *access_token* (query-string) - OAuth access token.
5655    /// * *alt* (query-string) - Data format for response.
5656    /// * *callback* (query-string) - JSONP
5657    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
5658    /// * *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.
5659    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
5660    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
5661    /// * *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.
5662    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
5663    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
5664    pub fn param<T>(mut self, name: T, value: T) -> UserDraftUpdateCall<'a, C>
5665    where
5666        T: AsRef<str>,
5667    {
5668        self._additional_params
5669            .insert(name.as_ref().to_string(), value.as_ref().to_string());
5670        self
5671    }
5672
5673    /// Identifies the authorization scope for the method you are building.
5674    ///
5675    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
5676    /// [`Scope::Gmai`].
5677    ///
5678    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
5679    /// tokens for more than one scope.
5680    ///
5681    /// Usually there is more than one suitable scope to authorize an operation, some of which may
5682    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
5683    /// sufficient, a read-write scope will do as well.
5684    pub fn add_scope<St>(mut self, scope: St) -> UserDraftUpdateCall<'a, C>
5685    where
5686        St: AsRef<str>,
5687    {
5688        self._scopes.insert(String::from(scope.as_ref()));
5689        self
5690    }
5691    /// Identifies the authorization scope(s) for the method you are building.
5692    ///
5693    /// See [`Self::add_scope()`] for details.
5694    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserDraftUpdateCall<'a, C>
5695    where
5696        I: IntoIterator<Item = St>,
5697        St: AsRef<str>,
5698    {
5699        self._scopes
5700            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
5701        self
5702    }
5703
5704    /// Removes all scopes, and no default scope will be used either.
5705    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
5706    /// for details).
5707    pub fn clear_scopes(mut self) -> UserDraftUpdateCall<'a, C> {
5708        self._scopes.clear();
5709        self
5710    }
5711}
5712
5713/// Lists the history of all changes to the given mailbox. History results are returned in chronological order (increasing `historyId`).
5714///
5715/// A builder for the *history.list* method supported by a *user* resource.
5716/// It is not used directly, but through a [`UserMethods`] instance.
5717///
5718/// # Example
5719///
5720/// Instantiate a resource method builder
5721///
5722/// ```test_harness,no_run
5723/// # extern crate hyper;
5724/// # extern crate hyper_rustls;
5725/// # extern crate google_gmail1 as gmail1;
5726/// # async fn dox() {
5727/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
5728///
5729/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
5730/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
5731/// #     secret,
5732/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
5733/// # ).build().await.unwrap();
5734///
5735/// # let client = hyper_util::client::legacy::Client::builder(
5736/// #     hyper_util::rt::TokioExecutor::new()
5737/// # )
5738/// # .build(
5739/// #     hyper_rustls::HttpsConnectorBuilder::new()
5740/// #         .with_native_roots()
5741/// #         .unwrap()
5742/// #         .https_or_http()
5743/// #         .enable_http1()
5744/// #         .build()
5745/// # );
5746/// # let mut hub = Gmail::new(client, auth);
5747/// // You can configure optional parameters by calling the respective setters at will, and
5748/// // execute the final call using `doit()`.
5749/// // Values shown here are possibly random and not representative !
5750/// let result = hub.users().history_list("userId")
5751///              .start_history_id(31)
5752///              .page_token("sed")
5753///              .max_results(40)
5754///              .label_id("Stet")
5755///              .add_history_types("kasd")
5756///              .doit().await;
5757/// # }
5758/// ```
5759pub struct UserHistoryListCall<'a, C>
5760where
5761    C: 'a,
5762{
5763    hub: &'a Gmail<C>,
5764    _user_id: String,
5765    _start_history_id: Option<u64>,
5766    _page_token: Option<String>,
5767    _max_results: Option<u32>,
5768    _label_id: Option<String>,
5769    _history_types: Vec<String>,
5770    _delegate: Option<&'a mut dyn common::Delegate>,
5771    _additional_params: HashMap<String, String>,
5772    _scopes: BTreeSet<String>,
5773}
5774
5775impl<'a, C> common::CallBuilder for UserHistoryListCall<'a, C> {}
5776
5777impl<'a, C> UserHistoryListCall<'a, C>
5778where
5779    C: common::Connector,
5780{
5781    /// Perform the operation you have build so far.
5782    pub async fn doit(mut self) -> common::Result<(common::Response, ListHistoryResponse)> {
5783        use std::borrow::Cow;
5784        use std::io::{Read, Seek};
5785
5786        use common::{url::Params, ToParts};
5787        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
5788
5789        let mut dd = common::DefaultDelegate;
5790        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
5791        dlg.begin(common::MethodInfo {
5792            id: "gmail.users.history.list",
5793            http_method: hyper::Method::GET,
5794        });
5795
5796        for &field in [
5797            "alt",
5798            "userId",
5799            "startHistoryId",
5800            "pageToken",
5801            "maxResults",
5802            "labelId",
5803            "historyTypes",
5804        ]
5805        .iter()
5806        {
5807            if self._additional_params.contains_key(field) {
5808                dlg.finished(false);
5809                return Err(common::Error::FieldClash(field));
5810            }
5811        }
5812
5813        let mut params = Params::with_capacity(8 + self._additional_params.len());
5814        params.push("userId", self._user_id);
5815        if let Some(value) = self._start_history_id.as_ref() {
5816            params.push("startHistoryId", value.to_string());
5817        }
5818        if let Some(value) = self._page_token.as_ref() {
5819            params.push("pageToken", value);
5820        }
5821        if let Some(value) = self._max_results.as_ref() {
5822            params.push("maxResults", value.to_string());
5823        }
5824        if let Some(value) = self._label_id.as_ref() {
5825            params.push("labelId", value);
5826        }
5827        if !self._history_types.is_empty() {
5828            for f in self._history_types.iter() {
5829                params.push("historyTypes", f);
5830            }
5831        }
5832
5833        params.extend(self._additional_params.iter());
5834
5835        params.push("alt", "json");
5836        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/history";
5837        if self._scopes.is_empty() {
5838            self._scopes.insert(Scope::Readonly.as_ref().to_string());
5839        }
5840
5841        #[allow(clippy::single_element_loop)]
5842        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
5843            url = params.uri_replacement(url, param_name, find_this, false);
5844        }
5845        {
5846            let to_remove = ["userId"];
5847            params.remove_params(&to_remove);
5848        }
5849
5850        let url = params.parse_with_url(&url);
5851
5852        loop {
5853            let token = match self
5854                .hub
5855                .auth
5856                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
5857                .await
5858            {
5859                Ok(token) => token,
5860                Err(e) => match dlg.token(e) {
5861                    Ok(token) => token,
5862                    Err(e) => {
5863                        dlg.finished(false);
5864                        return Err(common::Error::MissingToken(e));
5865                    }
5866                },
5867            };
5868            let mut req_result = {
5869                let client = &self.hub.client;
5870                dlg.pre_request();
5871                let mut req_builder = hyper::Request::builder()
5872                    .method(hyper::Method::GET)
5873                    .uri(url.as_str())
5874                    .header(USER_AGENT, self.hub._user_agent.clone());
5875
5876                if let Some(token) = token.as_ref() {
5877                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
5878                }
5879
5880                let request = req_builder
5881                    .header(CONTENT_LENGTH, 0_u64)
5882                    .body(common::to_body::<String>(None));
5883
5884                client.request(request.unwrap()).await
5885            };
5886
5887            match req_result {
5888                Err(err) => {
5889                    if let common::Retry::After(d) = dlg.http_error(&err) {
5890                        sleep(d).await;
5891                        continue;
5892                    }
5893                    dlg.finished(false);
5894                    return Err(common::Error::HttpError(err));
5895                }
5896                Ok(res) => {
5897                    let (mut parts, body) = res.into_parts();
5898                    let mut body = common::Body::new(body);
5899                    if !parts.status.is_success() {
5900                        let bytes = common::to_bytes(body).await.unwrap_or_default();
5901                        let error = serde_json::from_str(&common::to_string(&bytes));
5902                        let response = common::to_response(parts, bytes.into());
5903
5904                        if let common::Retry::After(d) =
5905                            dlg.http_failure(&response, error.as_ref().ok())
5906                        {
5907                            sleep(d).await;
5908                            continue;
5909                        }
5910
5911                        dlg.finished(false);
5912
5913                        return Err(match error {
5914                            Ok(value) => common::Error::BadRequest(value),
5915                            _ => common::Error::Failure(response),
5916                        });
5917                    }
5918                    let response = {
5919                        let bytes = common::to_bytes(body).await.unwrap_or_default();
5920                        let encoded = common::to_string(&bytes);
5921                        match serde_json::from_str(&encoded) {
5922                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
5923                            Err(error) => {
5924                                dlg.response_json_decode_error(&encoded, &error);
5925                                return Err(common::Error::JsonDecodeError(
5926                                    encoded.to_string(),
5927                                    error,
5928                                ));
5929                            }
5930                        }
5931                    };
5932
5933                    dlg.finished(true);
5934                    return Ok(response);
5935                }
5936            }
5937        }
5938    }
5939
5940    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
5941    ///
5942    /// Sets the *user id* path property to the given value.
5943    ///
5944    /// Even though the property as already been set when instantiating this call,
5945    /// we provide this method for API completeness.
5946    pub fn user_id(mut self, new_value: &str) -> UserHistoryListCall<'a, C> {
5947        self._user_id = new_value.to_string();
5948        self
5949    }
5950    /// Required. Returns history records after the specified `startHistoryId`. The supplied `startHistoryId` should be obtained from the `historyId` of a message, thread, or previous `list` response. History IDs increase chronologically but are not contiguous with random gaps in between valid IDs. Supplying an invalid or out of date `startHistoryId` typically returns an `HTTP 404` error code. A `historyId` is typically valid for at least a week, but in some rare circumstances may be valid for only a few hours. If you receive an `HTTP 404` error response, your application should perform a full sync. If you receive no `nextPageToken` in the response, there are no updates to retrieve and you can store the returned `historyId` for a future request.
5951    ///
5952    /// Sets the *start history id* query property to the given value.
5953    pub fn start_history_id(mut self, new_value: u64) -> UserHistoryListCall<'a, C> {
5954        self._start_history_id = Some(new_value);
5955        self
5956    }
5957    /// Page token to retrieve a specific page of results in the list.
5958    ///
5959    /// Sets the *page token* query property to the given value.
5960    pub fn page_token(mut self, new_value: &str) -> UserHistoryListCall<'a, C> {
5961        self._page_token = Some(new_value.to_string());
5962        self
5963    }
5964    /// Maximum number of history records to return. This field defaults to 100. The maximum allowed value for this field is 500.
5965    ///
5966    /// Sets the *max results* query property to the given value.
5967    pub fn max_results(mut self, new_value: u32) -> UserHistoryListCall<'a, C> {
5968        self._max_results = Some(new_value);
5969        self
5970    }
5971    /// Only return messages with a label matching the ID.
5972    ///
5973    /// Sets the *label id* query property to the given value.
5974    pub fn label_id(mut self, new_value: &str) -> UserHistoryListCall<'a, C> {
5975        self._label_id = Some(new_value.to_string());
5976        self
5977    }
5978    /// History types to be returned by the function
5979    ///
5980    /// Append the given value to the *history types* query property.
5981    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
5982    pub fn add_history_types(mut self, new_value: &str) -> UserHistoryListCall<'a, C> {
5983        self._history_types.push(new_value.to_string());
5984        self
5985    }
5986    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
5987    /// while executing the actual API request.
5988    ///
5989    /// ````text
5990    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
5991    /// ````
5992    ///
5993    /// Sets the *delegate* property to the given value.
5994    pub fn delegate(
5995        mut self,
5996        new_value: &'a mut dyn common::Delegate,
5997    ) -> UserHistoryListCall<'a, C> {
5998        self._delegate = Some(new_value);
5999        self
6000    }
6001
6002    /// Set any additional parameter of the query string used in the request.
6003    /// It should be used to set parameters which are not yet available through their own
6004    /// setters.
6005    ///
6006    /// Please note that this method must not be used to set any of the known parameters
6007    /// which have their own setter method. If done anyway, the request will fail.
6008    ///
6009    /// # Additional Parameters
6010    ///
6011    /// * *$.xgafv* (query-string) - V1 error format.
6012    /// * *access_token* (query-string) - OAuth access token.
6013    /// * *alt* (query-string) - Data format for response.
6014    /// * *callback* (query-string) - JSONP
6015    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
6016    /// * *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.
6017    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
6018    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
6019    /// * *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.
6020    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
6021    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
6022    pub fn param<T>(mut self, name: T, value: T) -> UserHistoryListCall<'a, C>
6023    where
6024        T: AsRef<str>,
6025    {
6026        self._additional_params
6027            .insert(name.as_ref().to_string(), value.as_ref().to_string());
6028        self
6029    }
6030
6031    /// Identifies the authorization scope for the method you are building.
6032    ///
6033    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
6034    /// [`Scope::Readonly`].
6035    ///
6036    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
6037    /// tokens for more than one scope.
6038    ///
6039    /// Usually there is more than one suitable scope to authorize an operation, some of which may
6040    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
6041    /// sufficient, a read-write scope will do as well.
6042    pub fn add_scope<St>(mut self, scope: St) -> UserHistoryListCall<'a, C>
6043    where
6044        St: AsRef<str>,
6045    {
6046        self._scopes.insert(String::from(scope.as_ref()));
6047        self
6048    }
6049    /// Identifies the authorization scope(s) for the method you are building.
6050    ///
6051    /// See [`Self::add_scope()`] for details.
6052    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserHistoryListCall<'a, C>
6053    where
6054        I: IntoIterator<Item = St>,
6055        St: AsRef<str>,
6056    {
6057        self._scopes
6058            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
6059        self
6060    }
6061
6062    /// Removes all scopes, and no default scope will be used either.
6063    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
6064    /// for details).
6065    pub fn clear_scopes(mut self) -> UserHistoryListCall<'a, C> {
6066        self._scopes.clear();
6067        self
6068    }
6069}
6070
6071/// Creates a new label.
6072///
6073/// A builder for the *labels.create* method supported by a *user* resource.
6074/// It is not used directly, but through a [`UserMethods`] instance.
6075///
6076/// # Example
6077///
6078/// Instantiate a resource method builder
6079///
6080/// ```test_harness,no_run
6081/// # extern crate hyper;
6082/// # extern crate hyper_rustls;
6083/// # extern crate google_gmail1 as gmail1;
6084/// use gmail1::api::Label;
6085/// # async fn dox() {
6086/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
6087///
6088/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
6089/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
6090/// #     secret,
6091/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
6092/// # ).build().await.unwrap();
6093///
6094/// # let client = hyper_util::client::legacy::Client::builder(
6095/// #     hyper_util::rt::TokioExecutor::new()
6096/// # )
6097/// # .build(
6098/// #     hyper_rustls::HttpsConnectorBuilder::new()
6099/// #         .with_native_roots()
6100/// #         .unwrap()
6101/// #         .https_or_http()
6102/// #         .enable_http1()
6103/// #         .build()
6104/// # );
6105/// # let mut hub = Gmail::new(client, auth);
6106/// // As the method needs a request, you would usually fill it with the desired information
6107/// // into the respective structure. Some of the parts shown here might not be applicable !
6108/// // Values shown here are possibly random and not representative !
6109/// let mut req = Label::default();
6110///
6111/// // You can configure optional parameters by calling the respective setters at will, and
6112/// // execute the final call using `doit()`.
6113/// // Values shown here are possibly random and not representative !
6114/// let result = hub.users().labels_create(req, "userId")
6115///              .doit().await;
6116/// # }
6117/// ```
6118pub struct UserLabelCreateCall<'a, C>
6119where
6120    C: 'a,
6121{
6122    hub: &'a Gmail<C>,
6123    _request: Label,
6124    _user_id: String,
6125    _delegate: Option<&'a mut dyn common::Delegate>,
6126    _additional_params: HashMap<String, String>,
6127    _scopes: BTreeSet<String>,
6128}
6129
6130impl<'a, C> common::CallBuilder for UserLabelCreateCall<'a, C> {}
6131
6132impl<'a, C> UserLabelCreateCall<'a, C>
6133where
6134    C: common::Connector,
6135{
6136    /// Perform the operation you have build so far.
6137    pub async fn doit(mut self) -> common::Result<(common::Response, Label)> {
6138        use std::borrow::Cow;
6139        use std::io::{Read, Seek};
6140
6141        use common::{url::Params, ToParts};
6142        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
6143
6144        let mut dd = common::DefaultDelegate;
6145        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
6146        dlg.begin(common::MethodInfo {
6147            id: "gmail.users.labels.create",
6148            http_method: hyper::Method::POST,
6149        });
6150
6151        for &field in ["alt", "userId"].iter() {
6152            if self._additional_params.contains_key(field) {
6153                dlg.finished(false);
6154                return Err(common::Error::FieldClash(field));
6155            }
6156        }
6157
6158        let mut params = Params::with_capacity(4 + self._additional_params.len());
6159        params.push("userId", self._user_id);
6160
6161        params.extend(self._additional_params.iter());
6162
6163        params.push("alt", "json");
6164        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/labels";
6165        if self._scopes.is_empty() {
6166            self._scopes.insert(Scope::Gmai.as_ref().to_string());
6167        }
6168
6169        #[allow(clippy::single_element_loop)]
6170        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
6171            url = params.uri_replacement(url, param_name, find_this, false);
6172        }
6173        {
6174            let to_remove = ["userId"];
6175            params.remove_params(&to_remove);
6176        }
6177
6178        let url = params.parse_with_url(&url);
6179
6180        let mut json_mime_type = mime::APPLICATION_JSON;
6181        let mut request_value_reader = {
6182            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
6183            common::remove_json_null_values(&mut value);
6184            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
6185            serde_json::to_writer(&mut dst, &value).unwrap();
6186            dst
6187        };
6188        let request_size = request_value_reader
6189            .seek(std::io::SeekFrom::End(0))
6190            .unwrap();
6191        request_value_reader
6192            .seek(std::io::SeekFrom::Start(0))
6193            .unwrap();
6194
6195        loop {
6196            let token = match self
6197                .hub
6198                .auth
6199                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
6200                .await
6201            {
6202                Ok(token) => token,
6203                Err(e) => match dlg.token(e) {
6204                    Ok(token) => token,
6205                    Err(e) => {
6206                        dlg.finished(false);
6207                        return Err(common::Error::MissingToken(e));
6208                    }
6209                },
6210            };
6211            request_value_reader
6212                .seek(std::io::SeekFrom::Start(0))
6213                .unwrap();
6214            let mut req_result = {
6215                let client = &self.hub.client;
6216                dlg.pre_request();
6217                let mut req_builder = hyper::Request::builder()
6218                    .method(hyper::Method::POST)
6219                    .uri(url.as_str())
6220                    .header(USER_AGENT, self.hub._user_agent.clone());
6221
6222                if let Some(token) = token.as_ref() {
6223                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
6224                }
6225
6226                let request = req_builder
6227                    .header(CONTENT_TYPE, json_mime_type.to_string())
6228                    .header(CONTENT_LENGTH, request_size as u64)
6229                    .body(common::to_body(
6230                        request_value_reader.get_ref().clone().into(),
6231                    ));
6232
6233                client.request(request.unwrap()).await
6234            };
6235
6236            match req_result {
6237                Err(err) => {
6238                    if let common::Retry::After(d) = dlg.http_error(&err) {
6239                        sleep(d).await;
6240                        continue;
6241                    }
6242                    dlg.finished(false);
6243                    return Err(common::Error::HttpError(err));
6244                }
6245                Ok(res) => {
6246                    let (mut parts, body) = res.into_parts();
6247                    let mut body = common::Body::new(body);
6248                    if !parts.status.is_success() {
6249                        let bytes = common::to_bytes(body).await.unwrap_or_default();
6250                        let error = serde_json::from_str(&common::to_string(&bytes));
6251                        let response = common::to_response(parts, bytes.into());
6252
6253                        if let common::Retry::After(d) =
6254                            dlg.http_failure(&response, error.as_ref().ok())
6255                        {
6256                            sleep(d).await;
6257                            continue;
6258                        }
6259
6260                        dlg.finished(false);
6261
6262                        return Err(match error {
6263                            Ok(value) => common::Error::BadRequest(value),
6264                            _ => common::Error::Failure(response),
6265                        });
6266                    }
6267                    let response = {
6268                        let bytes = common::to_bytes(body).await.unwrap_or_default();
6269                        let encoded = common::to_string(&bytes);
6270                        match serde_json::from_str(&encoded) {
6271                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
6272                            Err(error) => {
6273                                dlg.response_json_decode_error(&encoded, &error);
6274                                return Err(common::Error::JsonDecodeError(
6275                                    encoded.to_string(),
6276                                    error,
6277                                ));
6278                            }
6279                        }
6280                    };
6281
6282                    dlg.finished(true);
6283                    return Ok(response);
6284                }
6285            }
6286        }
6287    }
6288
6289    ///
6290    /// Sets the *request* property to the given value.
6291    ///
6292    /// Even though the property as already been set when instantiating this call,
6293    /// we provide this method for API completeness.
6294    pub fn request(mut self, new_value: Label) -> UserLabelCreateCall<'a, C> {
6295        self._request = new_value;
6296        self
6297    }
6298    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
6299    ///
6300    /// Sets the *user id* path property to the given value.
6301    ///
6302    /// Even though the property as already been set when instantiating this call,
6303    /// we provide this method for API completeness.
6304    pub fn user_id(mut self, new_value: &str) -> UserLabelCreateCall<'a, C> {
6305        self._user_id = new_value.to_string();
6306        self
6307    }
6308    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
6309    /// while executing the actual API request.
6310    ///
6311    /// ````text
6312    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
6313    /// ````
6314    ///
6315    /// Sets the *delegate* property to the given value.
6316    pub fn delegate(
6317        mut self,
6318        new_value: &'a mut dyn common::Delegate,
6319    ) -> UserLabelCreateCall<'a, C> {
6320        self._delegate = Some(new_value);
6321        self
6322    }
6323
6324    /// Set any additional parameter of the query string used in the request.
6325    /// It should be used to set parameters which are not yet available through their own
6326    /// setters.
6327    ///
6328    /// Please note that this method must not be used to set any of the known parameters
6329    /// which have their own setter method. If done anyway, the request will fail.
6330    ///
6331    /// # Additional Parameters
6332    ///
6333    /// * *$.xgafv* (query-string) - V1 error format.
6334    /// * *access_token* (query-string) - OAuth access token.
6335    /// * *alt* (query-string) - Data format for response.
6336    /// * *callback* (query-string) - JSONP
6337    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
6338    /// * *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.
6339    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
6340    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
6341    /// * *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.
6342    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
6343    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
6344    pub fn param<T>(mut self, name: T, value: T) -> UserLabelCreateCall<'a, C>
6345    where
6346        T: AsRef<str>,
6347    {
6348        self._additional_params
6349            .insert(name.as_ref().to_string(), value.as_ref().to_string());
6350        self
6351    }
6352
6353    /// Identifies the authorization scope for the method you are building.
6354    ///
6355    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
6356    /// [`Scope::Gmai`].
6357    ///
6358    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
6359    /// tokens for more than one scope.
6360    ///
6361    /// Usually there is more than one suitable scope to authorize an operation, some of which may
6362    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
6363    /// sufficient, a read-write scope will do as well.
6364    pub fn add_scope<St>(mut self, scope: St) -> UserLabelCreateCall<'a, C>
6365    where
6366        St: AsRef<str>,
6367    {
6368        self._scopes.insert(String::from(scope.as_ref()));
6369        self
6370    }
6371    /// Identifies the authorization scope(s) for the method you are building.
6372    ///
6373    /// See [`Self::add_scope()`] for details.
6374    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserLabelCreateCall<'a, C>
6375    where
6376        I: IntoIterator<Item = St>,
6377        St: AsRef<str>,
6378    {
6379        self._scopes
6380            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
6381        self
6382    }
6383
6384    /// Removes all scopes, and no default scope will be used either.
6385    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
6386    /// for details).
6387    pub fn clear_scopes(mut self) -> UserLabelCreateCall<'a, C> {
6388        self._scopes.clear();
6389        self
6390    }
6391}
6392
6393/// Immediately and permanently deletes the specified label and removes it from any messages and threads that it is applied to.
6394///
6395/// A builder for the *labels.delete* method supported by a *user* resource.
6396/// It is not used directly, but through a [`UserMethods`] instance.
6397///
6398/// # Example
6399///
6400/// Instantiate a resource method builder
6401///
6402/// ```test_harness,no_run
6403/// # extern crate hyper;
6404/// # extern crate hyper_rustls;
6405/// # extern crate google_gmail1 as gmail1;
6406/// # async fn dox() {
6407/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
6408///
6409/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
6410/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
6411/// #     secret,
6412/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
6413/// # ).build().await.unwrap();
6414///
6415/// # let client = hyper_util::client::legacy::Client::builder(
6416/// #     hyper_util::rt::TokioExecutor::new()
6417/// # )
6418/// # .build(
6419/// #     hyper_rustls::HttpsConnectorBuilder::new()
6420/// #         .with_native_roots()
6421/// #         .unwrap()
6422/// #         .https_or_http()
6423/// #         .enable_http1()
6424/// #         .build()
6425/// # );
6426/// # let mut hub = Gmail::new(client, auth);
6427/// // You can configure optional parameters by calling the respective setters at will, and
6428/// // execute the final call using `doit()`.
6429/// // Values shown here are possibly random and not representative !
6430/// let result = hub.users().labels_delete("userId", "id")
6431///              .doit().await;
6432/// # }
6433/// ```
6434pub struct UserLabelDeleteCall<'a, C>
6435where
6436    C: 'a,
6437{
6438    hub: &'a Gmail<C>,
6439    _user_id: String,
6440    _id: String,
6441    _delegate: Option<&'a mut dyn common::Delegate>,
6442    _additional_params: HashMap<String, String>,
6443    _scopes: BTreeSet<String>,
6444}
6445
6446impl<'a, C> common::CallBuilder for UserLabelDeleteCall<'a, C> {}
6447
6448impl<'a, C> UserLabelDeleteCall<'a, C>
6449where
6450    C: common::Connector,
6451{
6452    /// Perform the operation you have build so far.
6453    pub async fn doit(mut self) -> common::Result<common::Response> {
6454        use std::borrow::Cow;
6455        use std::io::{Read, Seek};
6456
6457        use common::{url::Params, ToParts};
6458        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
6459
6460        let mut dd = common::DefaultDelegate;
6461        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
6462        dlg.begin(common::MethodInfo {
6463            id: "gmail.users.labels.delete",
6464            http_method: hyper::Method::DELETE,
6465        });
6466
6467        for &field in ["userId", "id"].iter() {
6468            if self._additional_params.contains_key(field) {
6469                dlg.finished(false);
6470                return Err(common::Error::FieldClash(field));
6471            }
6472        }
6473
6474        let mut params = Params::with_capacity(3 + self._additional_params.len());
6475        params.push("userId", self._user_id);
6476        params.push("id", self._id);
6477
6478        params.extend(self._additional_params.iter());
6479
6480        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/labels/{id}";
6481        if self._scopes.is_empty() {
6482            self._scopes.insert(Scope::Gmai.as_ref().to_string());
6483        }
6484
6485        #[allow(clippy::single_element_loop)]
6486        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
6487            url = params.uri_replacement(url, param_name, find_this, false);
6488        }
6489        {
6490            let to_remove = ["id", "userId"];
6491            params.remove_params(&to_remove);
6492        }
6493
6494        let url = params.parse_with_url(&url);
6495
6496        loop {
6497            let token = match self
6498                .hub
6499                .auth
6500                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
6501                .await
6502            {
6503                Ok(token) => token,
6504                Err(e) => match dlg.token(e) {
6505                    Ok(token) => token,
6506                    Err(e) => {
6507                        dlg.finished(false);
6508                        return Err(common::Error::MissingToken(e));
6509                    }
6510                },
6511            };
6512            let mut req_result = {
6513                let client = &self.hub.client;
6514                dlg.pre_request();
6515                let mut req_builder = hyper::Request::builder()
6516                    .method(hyper::Method::DELETE)
6517                    .uri(url.as_str())
6518                    .header(USER_AGENT, self.hub._user_agent.clone());
6519
6520                if let Some(token) = token.as_ref() {
6521                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
6522                }
6523
6524                let request = req_builder
6525                    .header(CONTENT_LENGTH, 0_u64)
6526                    .body(common::to_body::<String>(None));
6527
6528                client.request(request.unwrap()).await
6529            };
6530
6531            match req_result {
6532                Err(err) => {
6533                    if let common::Retry::After(d) = dlg.http_error(&err) {
6534                        sleep(d).await;
6535                        continue;
6536                    }
6537                    dlg.finished(false);
6538                    return Err(common::Error::HttpError(err));
6539                }
6540                Ok(res) => {
6541                    let (mut parts, body) = res.into_parts();
6542                    let mut body = common::Body::new(body);
6543                    if !parts.status.is_success() {
6544                        let bytes = common::to_bytes(body).await.unwrap_or_default();
6545                        let error = serde_json::from_str(&common::to_string(&bytes));
6546                        let response = common::to_response(parts, bytes.into());
6547
6548                        if let common::Retry::After(d) =
6549                            dlg.http_failure(&response, error.as_ref().ok())
6550                        {
6551                            sleep(d).await;
6552                            continue;
6553                        }
6554
6555                        dlg.finished(false);
6556
6557                        return Err(match error {
6558                            Ok(value) => common::Error::BadRequest(value),
6559                            _ => common::Error::Failure(response),
6560                        });
6561                    }
6562                    let response = common::Response::from_parts(parts, body);
6563
6564                    dlg.finished(true);
6565                    return Ok(response);
6566                }
6567            }
6568        }
6569    }
6570
6571    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
6572    ///
6573    /// Sets the *user id* path property to the given value.
6574    ///
6575    /// Even though the property as already been set when instantiating this call,
6576    /// we provide this method for API completeness.
6577    pub fn user_id(mut self, new_value: &str) -> UserLabelDeleteCall<'a, C> {
6578        self._user_id = new_value.to_string();
6579        self
6580    }
6581    /// The ID of the label to delete.
6582    ///
6583    /// Sets the *id* path property to the given value.
6584    ///
6585    /// Even though the property as already been set when instantiating this call,
6586    /// we provide this method for API completeness.
6587    pub fn id(mut self, new_value: &str) -> UserLabelDeleteCall<'a, C> {
6588        self._id = new_value.to_string();
6589        self
6590    }
6591    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
6592    /// while executing the actual API request.
6593    ///
6594    /// ````text
6595    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
6596    /// ````
6597    ///
6598    /// Sets the *delegate* property to the given value.
6599    pub fn delegate(
6600        mut self,
6601        new_value: &'a mut dyn common::Delegate,
6602    ) -> UserLabelDeleteCall<'a, C> {
6603        self._delegate = Some(new_value);
6604        self
6605    }
6606
6607    /// Set any additional parameter of the query string used in the request.
6608    /// It should be used to set parameters which are not yet available through their own
6609    /// setters.
6610    ///
6611    /// Please note that this method must not be used to set any of the known parameters
6612    /// which have their own setter method. If done anyway, the request will fail.
6613    ///
6614    /// # Additional Parameters
6615    ///
6616    /// * *$.xgafv* (query-string) - V1 error format.
6617    /// * *access_token* (query-string) - OAuth access token.
6618    /// * *alt* (query-string) - Data format for response.
6619    /// * *callback* (query-string) - JSONP
6620    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
6621    /// * *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.
6622    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
6623    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
6624    /// * *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.
6625    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
6626    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
6627    pub fn param<T>(mut self, name: T, value: T) -> UserLabelDeleteCall<'a, C>
6628    where
6629        T: AsRef<str>,
6630    {
6631        self._additional_params
6632            .insert(name.as_ref().to_string(), value.as_ref().to_string());
6633        self
6634    }
6635
6636    /// Identifies the authorization scope for the method you are building.
6637    ///
6638    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
6639    /// [`Scope::Gmai`].
6640    ///
6641    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
6642    /// tokens for more than one scope.
6643    ///
6644    /// Usually there is more than one suitable scope to authorize an operation, some of which may
6645    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
6646    /// sufficient, a read-write scope will do as well.
6647    pub fn add_scope<St>(mut self, scope: St) -> UserLabelDeleteCall<'a, C>
6648    where
6649        St: AsRef<str>,
6650    {
6651        self._scopes.insert(String::from(scope.as_ref()));
6652        self
6653    }
6654    /// Identifies the authorization scope(s) for the method you are building.
6655    ///
6656    /// See [`Self::add_scope()`] for details.
6657    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserLabelDeleteCall<'a, C>
6658    where
6659        I: IntoIterator<Item = St>,
6660        St: AsRef<str>,
6661    {
6662        self._scopes
6663            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
6664        self
6665    }
6666
6667    /// Removes all scopes, and no default scope will be used either.
6668    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
6669    /// for details).
6670    pub fn clear_scopes(mut self) -> UserLabelDeleteCall<'a, C> {
6671        self._scopes.clear();
6672        self
6673    }
6674}
6675
6676/// Gets the specified label.
6677///
6678/// A builder for the *labels.get* method supported by a *user* resource.
6679/// It is not used directly, but through a [`UserMethods`] instance.
6680///
6681/// # Example
6682///
6683/// Instantiate a resource method builder
6684///
6685/// ```test_harness,no_run
6686/// # extern crate hyper;
6687/// # extern crate hyper_rustls;
6688/// # extern crate google_gmail1 as gmail1;
6689/// # async fn dox() {
6690/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
6691///
6692/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
6693/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
6694/// #     secret,
6695/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
6696/// # ).build().await.unwrap();
6697///
6698/// # let client = hyper_util::client::legacy::Client::builder(
6699/// #     hyper_util::rt::TokioExecutor::new()
6700/// # )
6701/// # .build(
6702/// #     hyper_rustls::HttpsConnectorBuilder::new()
6703/// #         .with_native_roots()
6704/// #         .unwrap()
6705/// #         .https_or_http()
6706/// #         .enable_http1()
6707/// #         .build()
6708/// # );
6709/// # let mut hub = Gmail::new(client, auth);
6710/// // You can configure optional parameters by calling the respective setters at will, and
6711/// // execute the final call using `doit()`.
6712/// // Values shown here are possibly random and not representative !
6713/// let result = hub.users().labels_get("userId", "id")
6714///              .doit().await;
6715/// # }
6716/// ```
6717pub struct UserLabelGetCall<'a, C>
6718where
6719    C: 'a,
6720{
6721    hub: &'a Gmail<C>,
6722    _user_id: String,
6723    _id: String,
6724    _delegate: Option<&'a mut dyn common::Delegate>,
6725    _additional_params: HashMap<String, String>,
6726    _scopes: BTreeSet<String>,
6727}
6728
6729impl<'a, C> common::CallBuilder for UserLabelGetCall<'a, C> {}
6730
6731impl<'a, C> UserLabelGetCall<'a, C>
6732where
6733    C: common::Connector,
6734{
6735    /// Perform the operation you have build so far.
6736    pub async fn doit(mut self) -> common::Result<(common::Response, Label)> {
6737        use std::borrow::Cow;
6738        use std::io::{Read, Seek};
6739
6740        use common::{url::Params, ToParts};
6741        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
6742
6743        let mut dd = common::DefaultDelegate;
6744        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
6745        dlg.begin(common::MethodInfo {
6746            id: "gmail.users.labels.get",
6747            http_method: hyper::Method::GET,
6748        });
6749
6750        for &field in ["alt", "userId", "id"].iter() {
6751            if self._additional_params.contains_key(field) {
6752                dlg.finished(false);
6753                return Err(common::Error::FieldClash(field));
6754            }
6755        }
6756
6757        let mut params = Params::with_capacity(4 + self._additional_params.len());
6758        params.push("userId", self._user_id);
6759        params.push("id", self._id);
6760
6761        params.extend(self._additional_params.iter());
6762
6763        params.push("alt", "json");
6764        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/labels/{id}";
6765        if self._scopes.is_empty() {
6766            self._scopes.insert(Scope::Readonly.as_ref().to_string());
6767        }
6768
6769        #[allow(clippy::single_element_loop)]
6770        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
6771            url = params.uri_replacement(url, param_name, find_this, false);
6772        }
6773        {
6774            let to_remove = ["id", "userId"];
6775            params.remove_params(&to_remove);
6776        }
6777
6778        let url = params.parse_with_url(&url);
6779
6780        loop {
6781            let token = match self
6782                .hub
6783                .auth
6784                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
6785                .await
6786            {
6787                Ok(token) => token,
6788                Err(e) => match dlg.token(e) {
6789                    Ok(token) => token,
6790                    Err(e) => {
6791                        dlg.finished(false);
6792                        return Err(common::Error::MissingToken(e));
6793                    }
6794                },
6795            };
6796            let mut req_result = {
6797                let client = &self.hub.client;
6798                dlg.pre_request();
6799                let mut req_builder = hyper::Request::builder()
6800                    .method(hyper::Method::GET)
6801                    .uri(url.as_str())
6802                    .header(USER_AGENT, self.hub._user_agent.clone());
6803
6804                if let Some(token) = token.as_ref() {
6805                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
6806                }
6807
6808                let request = req_builder
6809                    .header(CONTENT_LENGTH, 0_u64)
6810                    .body(common::to_body::<String>(None));
6811
6812                client.request(request.unwrap()).await
6813            };
6814
6815            match req_result {
6816                Err(err) => {
6817                    if let common::Retry::After(d) = dlg.http_error(&err) {
6818                        sleep(d).await;
6819                        continue;
6820                    }
6821                    dlg.finished(false);
6822                    return Err(common::Error::HttpError(err));
6823                }
6824                Ok(res) => {
6825                    let (mut parts, body) = res.into_parts();
6826                    let mut body = common::Body::new(body);
6827                    if !parts.status.is_success() {
6828                        let bytes = common::to_bytes(body).await.unwrap_or_default();
6829                        let error = serde_json::from_str(&common::to_string(&bytes));
6830                        let response = common::to_response(parts, bytes.into());
6831
6832                        if let common::Retry::After(d) =
6833                            dlg.http_failure(&response, error.as_ref().ok())
6834                        {
6835                            sleep(d).await;
6836                            continue;
6837                        }
6838
6839                        dlg.finished(false);
6840
6841                        return Err(match error {
6842                            Ok(value) => common::Error::BadRequest(value),
6843                            _ => common::Error::Failure(response),
6844                        });
6845                    }
6846                    let response = {
6847                        let bytes = common::to_bytes(body).await.unwrap_or_default();
6848                        let encoded = common::to_string(&bytes);
6849                        match serde_json::from_str(&encoded) {
6850                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
6851                            Err(error) => {
6852                                dlg.response_json_decode_error(&encoded, &error);
6853                                return Err(common::Error::JsonDecodeError(
6854                                    encoded.to_string(),
6855                                    error,
6856                                ));
6857                            }
6858                        }
6859                    };
6860
6861                    dlg.finished(true);
6862                    return Ok(response);
6863                }
6864            }
6865        }
6866    }
6867
6868    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
6869    ///
6870    /// Sets the *user id* path property to the given value.
6871    ///
6872    /// Even though the property as already been set when instantiating this call,
6873    /// we provide this method for API completeness.
6874    pub fn user_id(mut self, new_value: &str) -> UserLabelGetCall<'a, C> {
6875        self._user_id = new_value.to_string();
6876        self
6877    }
6878    /// The ID of the label to retrieve.
6879    ///
6880    /// Sets the *id* path property to the given value.
6881    ///
6882    /// Even though the property as already been set when instantiating this call,
6883    /// we provide this method for API completeness.
6884    pub fn id(mut self, new_value: &str) -> UserLabelGetCall<'a, C> {
6885        self._id = new_value.to_string();
6886        self
6887    }
6888    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
6889    /// while executing the actual API request.
6890    ///
6891    /// ````text
6892    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
6893    /// ````
6894    ///
6895    /// Sets the *delegate* property to the given value.
6896    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> UserLabelGetCall<'a, C> {
6897        self._delegate = Some(new_value);
6898        self
6899    }
6900
6901    /// Set any additional parameter of the query string used in the request.
6902    /// It should be used to set parameters which are not yet available through their own
6903    /// setters.
6904    ///
6905    /// Please note that this method must not be used to set any of the known parameters
6906    /// which have their own setter method. If done anyway, the request will fail.
6907    ///
6908    /// # Additional Parameters
6909    ///
6910    /// * *$.xgafv* (query-string) - V1 error format.
6911    /// * *access_token* (query-string) - OAuth access token.
6912    /// * *alt* (query-string) - Data format for response.
6913    /// * *callback* (query-string) - JSONP
6914    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
6915    /// * *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.
6916    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
6917    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
6918    /// * *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.
6919    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
6920    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
6921    pub fn param<T>(mut self, name: T, value: T) -> UserLabelGetCall<'a, C>
6922    where
6923        T: AsRef<str>,
6924    {
6925        self._additional_params
6926            .insert(name.as_ref().to_string(), value.as_ref().to_string());
6927        self
6928    }
6929
6930    /// Identifies the authorization scope for the method you are building.
6931    ///
6932    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
6933    /// [`Scope::Readonly`].
6934    ///
6935    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
6936    /// tokens for more than one scope.
6937    ///
6938    /// Usually there is more than one suitable scope to authorize an operation, some of which may
6939    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
6940    /// sufficient, a read-write scope will do as well.
6941    pub fn add_scope<St>(mut self, scope: St) -> UserLabelGetCall<'a, C>
6942    where
6943        St: AsRef<str>,
6944    {
6945        self._scopes.insert(String::from(scope.as_ref()));
6946        self
6947    }
6948    /// Identifies the authorization scope(s) for the method you are building.
6949    ///
6950    /// See [`Self::add_scope()`] for details.
6951    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserLabelGetCall<'a, C>
6952    where
6953        I: IntoIterator<Item = St>,
6954        St: AsRef<str>,
6955    {
6956        self._scopes
6957            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
6958        self
6959    }
6960
6961    /// Removes all scopes, and no default scope will be used either.
6962    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
6963    /// for details).
6964    pub fn clear_scopes(mut self) -> UserLabelGetCall<'a, C> {
6965        self._scopes.clear();
6966        self
6967    }
6968}
6969
6970/// Lists all labels in the user's mailbox.
6971///
6972/// A builder for the *labels.list* method supported by a *user* resource.
6973/// It is not used directly, but through a [`UserMethods`] instance.
6974///
6975/// # Example
6976///
6977/// Instantiate a resource method builder
6978///
6979/// ```test_harness,no_run
6980/// # extern crate hyper;
6981/// # extern crate hyper_rustls;
6982/// # extern crate google_gmail1 as gmail1;
6983/// # async fn dox() {
6984/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
6985///
6986/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
6987/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
6988/// #     secret,
6989/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
6990/// # ).build().await.unwrap();
6991///
6992/// # let client = hyper_util::client::legacy::Client::builder(
6993/// #     hyper_util::rt::TokioExecutor::new()
6994/// # )
6995/// # .build(
6996/// #     hyper_rustls::HttpsConnectorBuilder::new()
6997/// #         .with_native_roots()
6998/// #         .unwrap()
6999/// #         .https_or_http()
7000/// #         .enable_http1()
7001/// #         .build()
7002/// # );
7003/// # let mut hub = Gmail::new(client, auth);
7004/// // You can configure optional parameters by calling the respective setters at will, and
7005/// // execute the final call using `doit()`.
7006/// // Values shown here are possibly random and not representative !
7007/// let result = hub.users().labels_list("userId")
7008///              .doit().await;
7009/// # }
7010/// ```
7011pub struct UserLabelListCall<'a, C>
7012where
7013    C: 'a,
7014{
7015    hub: &'a Gmail<C>,
7016    _user_id: String,
7017    _delegate: Option<&'a mut dyn common::Delegate>,
7018    _additional_params: HashMap<String, String>,
7019    _scopes: BTreeSet<String>,
7020}
7021
7022impl<'a, C> common::CallBuilder for UserLabelListCall<'a, C> {}
7023
7024impl<'a, C> UserLabelListCall<'a, C>
7025where
7026    C: common::Connector,
7027{
7028    /// Perform the operation you have build so far.
7029    pub async fn doit(mut self) -> common::Result<(common::Response, ListLabelsResponse)> {
7030        use std::borrow::Cow;
7031        use std::io::{Read, Seek};
7032
7033        use common::{url::Params, ToParts};
7034        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
7035
7036        let mut dd = common::DefaultDelegate;
7037        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
7038        dlg.begin(common::MethodInfo {
7039            id: "gmail.users.labels.list",
7040            http_method: hyper::Method::GET,
7041        });
7042
7043        for &field in ["alt", "userId"].iter() {
7044            if self._additional_params.contains_key(field) {
7045                dlg.finished(false);
7046                return Err(common::Error::FieldClash(field));
7047            }
7048        }
7049
7050        let mut params = Params::with_capacity(3 + self._additional_params.len());
7051        params.push("userId", self._user_id);
7052
7053        params.extend(self._additional_params.iter());
7054
7055        params.push("alt", "json");
7056        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/labels";
7057        if self._scopes.is_empty() {
7058            self._scopes.insert(Scope::Readonly.as_ref().to_string());
7059        }
7060
7061        #[allow(clippy::single_element_loop)]
7062        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
7063            url = params.uri_replacement(url, param_name, find_this, false);
7064        }
7065        {
7066            let to_remove = ["userId"];
7067            params.remove_params(&to_remove);
7068        }
7069
7070        let url = params.parse_with_url(&url);
7071
7072        loop {
7073            let token = match self
7074                .hub
7075                .auth
7076                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
7077                .await
7078            {
7079                Ok(token) => token,
7080                Err(e) => match dlg.token(e) {
7081                    Ok(token) => token,
7082                    Err(e) => {
7083                        dlg.finished(false);
7084                        return Err(common::Error::MissingToken(e));
7085                    }
7086                },
7087            };
7088            let mut req_result = {
7089                let client = &self.hub.client;
7090                dlg.pre_request();
7091                let mut req_builder = hyper::Request::builder()
7092                    .method(hyper::Method::GET)
7093                    .uri(url.as_str())
7094                    .header(USER_AGENT, self.hub._user_agent.clone());
7095
7096                if let Some(token) = token.as_ref() {
7097                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
7098                }
7099
7100                let request = req_builder
7101                    .header(CONTENT_LENGTH, 0_u64)
7102                    .body(common::to_body::<String>(None));
7103
7104                client.request(request.unwrap()).await
7105            };
7106
7107            match req_result {
7108                Err(err) => {
7109                    if let common::Retry::After(d) = dlg.http_error(&err) {
7110                        sleep(d).await;
7111                        continue;
7112                    }
7113                    dlg.finished(false);
7114                    return Err(common::Error::HttpError(err));
7115                }
7116                Ok(res) => {
7117                    let (mut parts, body) = res.into_parts();
7118                    let mut body = common::Body::new(body);
7119                    if !parts.status.is_success() {
7120                        let bytes = common::to_bytes(body).await.unwrap_or_default();
7121                        let error = serde_json::from_str(&common::to_string(&bytes));
7122                        let response = common::to_response(parts, bytes.into());
7123
7124                        if let common::Retry::After(d) =
7125                            dlg.http_failure(&response, error.as_ref().ok())
7126                        {
7127                            sleep(d).await;
7128                            continue;
7129                        }
7130
7131                        dlg.finished(false);
7132
7133                        return Err(match error {
7134                            Ok(value) => common::Error::BadRequest(value),
7135                            _ => common::Error::Failure(response),
7136                        });
7137                    }
7138                    let response = {
7139                        let bytes = common::to_bytes(body).await.unwrap_or_default();
7140                        let encoded = common::to_string(&bytes);
7141                        match serde_json::from_str(&encoded) {
7142                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
7143                            Err(error) => {
7144                                dlg.response_json_decode_error(&encoded, &error);
7145                                return Err(common::Error::JsonDecodeError(
7146                                    encoded.to_string(),
7147                                    error,
7148                                ));
7149                            }
7150                        }
7151                    };
7152
7153                    dlg.finished(true);
7154                    return Ok(response);
7155                }
7156            }
7157        }
7158    }
7159
7160    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
7161    ///
7162    /// Sets the *user id* path property to the given value.
7163    ///
7164    /// Even though the property as already been set when instantiating this call,
7165    /// we provide this method for API completeness.
7166    pub fn user_id(mut self, new_value: &str) -> UserLabelListCall<'a, C> {
7167        self._user_id = new_value.to_string();
7168        self
7169    }
7170    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
7171    /// while executing the actual API request.
7172    ///
7173    /// ````text
7174    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
7175    /// ````
7176    ///
7177    /// Sets the *delegate* property to the given value.
7178    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> UserLabelListCall<'a, C> {
7179        self._delegate = Some(new_value);
7180        self
7181    }
7182
7183    /// Set any additional parameter of the query string used in the request.
7184    /// It should be used to set parameters which are not yet available through their own
7185    /// setters.
7186    ///
7187    /// Please note that this method must not be used to set any of the known parameters
7188    /// which have their own setter method. If done anyway, the request will fail.
7189    ///
7190    /// # Additional Parameters
7191    ///
7192    /// * *$.xgafv* (query-string) - V1 error format.
7193    /// * *access_token* (query-string) - OAuth access token.
7194    /// * *alt* (query-string) - Data format for response.
7195    /// * *callback* (query-string) - JSONP
7196    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
7197    /// * *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.
7198    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
7199    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
7200    /// * *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.
7201    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
7202    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
7203    pub fn param<T>(mut self, name: T, value: T) -> UserLabelListCall<'a, C>
7204    where
7205        T: AsRef<str>,
7206    {
7207        self._additional_params
7208            .insert(name.as_ref().to_string(), value.as_ref().to_string());
7209        self
7210    }
7211
7212    /// Identifies the authorization scope for the method you are building.
7213    ///
7214    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
7215    /// [`Scope::Readonly`].
7216    ///
7217    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
7218    /// tokens for more than one scope.
7219    ///
7220    /// Usually there is more than one suitable scope to authorize an operation, some of which may
7221    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
7222    /// sufficient, a read-write scope will do as well.
7223    pub fn add_scope<St>(mut self, scope: St) -> UserLabelListCall<'a, C>
7224    where
7225        St: AsRef<str>,
7226    {
7227        self._scopes.insert(String::from(scope.as_ref()));
7228        self
7229    }
7230    /// Identifies the authorization scope(s) for the method you are building.
7231    ///
7232    /// See [`Self::add_scope()`] for details.
7233    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserLabelListCall<'a, C>
7234    where
7235        I: IntoIterator<Item = St>,
7236        St: AsRef<str>,
7237    {
7238        self._scopes
7239            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
7240        self
7241    }
7242
7243    /// Removes all scopes, and no default scope will be used either.
7244    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
7245    /// for details).
7246    pub fn clear_scopes(mut self) -> UserLabelListCall<'a, C> {
7247        self._scopes.clear();
7248        self
7249    }
7250}
7251
7252/// Patch the specified label.
7253///
7254/// A builder for the *labels.patch* method supported by a *user* resource.
7255/// It is not used directly, but through a [`UserMethods`] instance.
7256///
7257/// # Example
7258///
7259/// Instantiate a resource method builder
7260///
7261/// ```test_harness,no_run
7262/// # extern crate hyper;
7263/// # extern crate hyper_rustls;
7264/// # extern crate google_gmail1 as gmail1;
7265/// use gmail1::api::Label;
7266/// # async fn dox() {
7267/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
7268///
7269/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
7270/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
7271/// #     secret,
7272/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
7273/// # ).build().await.unwrap();
7274///
7275/// # let client = hyper_util::client::legacy::Client::builder(
7276/// #     hyper_util::rt::TokioExecutor::new()
7277/// # )
7278/// # .build(
7279/// #     hyper_rustls::HttpsConnectorBuilder::new()
7280/// #         .with_native_roots()
7281/// #         .unwrap()
7282/// #         .https_or_http()
7283/// #         .enable_http1()
7284/// #         .build()
7285/// # );
7286/// # let mut hub = Gmail::new(client, auth);
7287/// // As the method needs a request, you would usually fill it with the desired information
7288/// // into the respective structure. Some of the parts shown here might not be applicable !
7289/// // Values shown here are possibly random and not representative !
7290/// let mut req = Label::default();
7291///
7292/// // You can configure optional parameters by calling the respective setters at will, and
7293/// // execute the final call using `doit()`.
7294/// // Values shown here are possibly random and not representative !
7295/// let result = hub.users().labels_patch(req, "userId", "id")
7296///              .doit().await;
7297/// # }
7298/// ```
7299pub struct UserLabelPatchCall<'a, C>
7300where
7301    C: 'a,
7302{
7303    hub: &'a Gmail<C>,
7304    _request: Label,
7305    _user_id: String,
7306    _id: String,
7307    _delegate: Option<&'a mut dyn common::Delegate>,
7308    _additional_params: HashMap<String, String>,
7309    _scopes: BTreeSet<String>,
7310}
7311
7312impl<'a, C> common::CallBuilder for UserLabelPatchCall<'a, C> {}
7313
7314impl<'a, C> UserLabelPatchCall<'a, C>
7315where
7316    C: common::Connector,
7317{
7318    /// Perform the operation you have build so far.
7319    pub async fn doit(mut self) -> common::Result<(common::Response, Label)> {
7320        use std::borrow::Cow;
7321        use std::io::{Read, Seek};
7322
7323        use common::{url::Params, ToParts};
7324        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
7325
7326        let mut dd = common::DefaultDelegate;
7327        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
7328        dlg.begin(common::MethodInfo {
7329            id: "gmail.users.labels.patch",
7330            http_method: hyper::Method::PATCH,
7331        });
7332
7333        for &field in ["alt", "userId", "id"].iter() {
7334            if self._additional_params.contains_key(field) {
7335                dlg.finished(false);
7336                return Err(common::Error::FieldClash(field));
7337            }
7338        }
7339
7340        let mut params = Params::with_capacity(5 + self._additional_params.len());
7341        params.push("userId", self._user_id);
7342        params.push("id", self._id);
7343
7344        params.extend(self._additional_params.iter());
7345
7346        params.push("alt", "json");
7347        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/labels/{id}";
7348        if self._scopes.is_empty() {
7349            self._scopes.insert(Scope::Gmai.as_ref().to_string());
7350        }
7351
7352        #[allow(clippy::single_element_loop)]
7353        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
7354            url = params.uri_replacement(url, param_name, find_this, false);
7355        }
7356        {
7357            let to_remove = ["id", "userId"];
7358            params.remove_params(&to_remove);
7359        }
7360
7361        let url = params.parse_with_url(&url);
7362
7363        let mut json_mime_type = mime::APPLICATION_JSON;
7364        let mut request_value_reader = {
7365            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
7366            common::remove_json_null_values(&mut value);
7367            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
7368            serde_json::to_writer(&mut dst, &value).unwrap();
7369            dst
7370        };
7371        let request_size = request_value_reader
7372            .seek(std::io::SeekFrom::End(0))
7373            .unwrap();
7374        request_value_reader
7375            .seek(std::io::SeekFrom::Start(0))
7376            .unwrap();
7377
7378        loop {
7379            let token = match self
7380                .hub
7381                .auth
7382                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
7383                .await
7384            {
7385                Ok(token) => token,
7386                Err(e) => match dlg.token(e) {
7387                    Ok(token) => token,
7388                    Err(e) => {
7389                        dlg.finished(false);
7390                        return Err(common::Error::MissingToken(e));
7391                    }
7392                },
7393            };
7394            request_value_reader
7395                .seek(std::io::SeekFrom::Start(0))
7396                .unwrap();
7397            let mut req_result = {
7398                let client = &self.hub.client;
7399                dlg.pre_request();
7400                let mut req_builder = hyper::Request::builder()
7401                    .method(hyper::Method::PATCH)
7402                    .uri(url.as_str())
7403                    .header(USER_AGENT, self.hub._user_agent.clone());
7404
7405                if let Some(token) = token.as_ref() {
7406                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
7407                }
7408
7409                let request = req_builder
7410                    .header(CONTENT_TYPE, json_mime_type.to_string())
7411                    .header(CONTENT_LENGTH, request_size as u64)
7412                    .body(common::to_body(
7413                        request_value_reader.get_ref().clone().into(),
7414                    ));
7415
7416                client.request(request.unwrap()).await
7417            };
7418
7419            match req_result {
7420                Err(err) => {
7421                    if let common::Retry::After(d) = dlg.http_error(&err) {
7422                        sleep(d).await;
7423                        continue;
7424                    }
7425                    dlg.finished(false);
7426                    return Err(common::Error::HttpError(err));
7427                }
7428                Ok(res) => {
7429                    let (mut parts, body) = res.into_parts();
7430                    let mut body = common::Body::new(body);
7431                    if !parts.status.is_success() {
7432                        let bytes = common::to_bytes(body).await.unwrap_or_default();
7433                        let error = serde_json::from_str(&common::to_string(&bytes));
7434                        let response = common::to_response(parts, bytes.into());
7435
7436                        if let common::Retry::After(d) =
7437                            dlg.http_failure(&response, error.as_ref().ok())
7438                        {
7439                            sleep(d).await;
7440                            continue;
7441                        }
7442
7443                        dlg.finished(false);
7444
7445                        return Err(match error {
7446                            Ok(value) => common::Error::BadRequest(value),
7447                            _ => common::Error::Failure(response),
7448                        });
7449                    }
7450                    let response = {
7451                        let bytes = common::to_bytes(body).await.unwrap_or_default();
7452                        let encoded = common::to_string(&bytes);
7453                        match serde_json::from_str(&encoded) {
7454                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
7455                            Err(error) => {
7456                                dlg.response_json_decode_error(&encoded, &error);
7457                                return Err(common::Error::JsonDecodeError(
7458                                    encoded.to_string(),
7459                                    error,
7460                                ));
7461                            }
7462                        }
7463                    };
7464
7465                    dlg.finished(true);
7466                    return Ok(response);
7467                }
7468            }
7469        }
7470    }
7471
7472    ///
7473    /// Sets the *request* property to the given value.
7474    ///
7475    /// Even though the property as already been set when instantiating this call,
7476    /// we provide this method for API completeness.
7477    pub fn request(mut self, new_value: Label) -> UserLabelPatchCall<'a, C> {
7478        self._request = new_value;
7479        self
7480    }
7481    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
7482    ///
7483    /// Sets the *user id* path property to the given value.
7484    ///
7485    /// Even though the property as already been set when instantiating this call,
7486    /// we provide this method for API completeness.
7487    pub fn user_id(mut self, new_value: &str) -> UserLabelPatchCall<'a, C> {
7488        self._user_id = new_value.to_string();
7489        self
7490    }
7491    /// The ID of the label to update.
7492    ///
7493    /// Sets the *id* path property to the given value.
7494    ///
7495    /// Even though the property as already been set when instantiating this call,
7496    /// we provide this method for API completeness.
7497    pub fn id(mut self, new_value: &str) -> UserLabelPatchCall<'a, C> {
7498        self._id = new_value.to_string();
7499        self
7500    }
7501    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
7502    /// while executing the actual API request.
7503    ///
7504    /// ````text
7505    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
7506    /// ````
7507    ///
7508    /// Sets the *delegate* property to the given value.
7509    pub fn delegate(
7510        mut self,
7511        new_value: &'a mut dyn common::Delegate,
7512    ) -> UserLabelPatchCall<'a, C> {
7513        self._delegate = Some(new_value);
7514        self
7515    }
7516
7517    /// Set any additional parameter of the query string used in the request.
7518    /// It should be used to set parameters which are not yet available through their own
7519    /// setters.
7520    ///
7521    /// Please note that this method must not be used to set any of the known parameters
7522    /// which have their own setter method. If done anyway, the request will fail.
7523    ///
7524    /// # Additional Parameters
7525    ///
7526    /// * *$.xgafv* (query-string) - V1 error format.
7527    /// * *access_token* (query-string) - OAuth access token.
7528    /// * *alt* (query-string) - Data format for response.
7529    /// * *callback* (query-string) - JSONP
7530    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
7531    /// * *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.
7532    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
7533    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
7534    /// * *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.
7535    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
7536    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
7537    pub fn param<T>(mut self, name: T, value: T) -> UserLabelPatchCall<'a, C>
7538    where
7539        T: AsRef<str>,
7540    {
7541        self._additional_params
7542            .insert(name.as_ref().to_string(), value.as_ref().to_string());
7543        self
7544    }
7545
7546    /// Identifies the authorization scope for the method you are building.
7547    ///
7548    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
7549    /// [`Scope::Gmai`].
7550    ///
7551    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
7552    /// tokens for more than one scope.
7553    ///
7554    /// Usually there is more than one suitable scope to authorize an operation, some of which may
7555    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
7556    /// sufficient, a read-write scope will do as well.
7557    pub fn add_scope<St>(mut self, scope: St) -> UserLabelPatchCall<'a, C>
7558    where
7559        St: AsRef<str>,
7560    {
7561        self._scopes.insert(String::from(scope.as_ref()));
7562        self
7563    }
7564    /// Identifies the authorization scope(s) for the method you are building.
7565    ///
7566    /// See [`Self::add_scope()`] for details.
7567    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserLabelPatchCall<'a, C>
7568    where
7569        I: IntoIterator<Item = St>,
7570        St: AsRef<str>,
7571    {
7572        self._scopes
7573            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
7574        self
7575    }
7576
7577    /// Removes all scopes, and no default scope will be used either.
7578    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
7579    /// for details).
7580    pub fn clear_scopes(mut self) -> UserLabelPatchCall<'a, C> {
7581        self._scopes.clear();
7582        self
7583    }
7584}
7585
7586/// Updates the specified label.
7587///
7588/// A builder for the *labels.update* method supported by a *user* resource.
7589/// It is not used directly, but through a [`UserMethods`] instance.
7590///
7591/// # Example
7592///
7593/// Instantiate a resource method builder
7594///
7595/// ```test_harness,no_run
7596/// # extern crate hyper;
7597/// # extern crate hyper_rustls;
7598/// # extern crate google_gmail1 as gmail1;
7599/// use gmail1::api::Label;
7600/// # async fn dox() {
7601/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
7602///
7603/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
7604/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
7605/// #     secret,
7606/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
7607/// # ).build().await.unwrap();
7608///
7609/// # let client = hyper_util::client::legacy::Client::builder(
7610/// #     hyper_util::rt::TokioExecutor::new()
7611/// # )
7612/// # .build(
7613/// #     hyper_rustls::HttpsConnectorBuilder::new()
7614/// #         .with_native_roots()
7615/// #         .unwrap()
7616/// #         .https_or_http()
7617/// #         .enable_http1()
7618/// #         .build()
7619/// # );
7620/// # let mut hub = Gmail::new(client, auth);
7621/// // As the method needs a request, you would usually fill it with the desired information
7622/// // into the respective structure. Some of the parts shown here might not be applicable !
7623/// // Values shown here are possibly random and not representative !
7624/// let mut req = Label::default();
7625///
7626/// // You can configure optional parameters by calling the respective setters at will, and
7627/// // execute the final call using `doit()`.
7628/// // Values shown here are possibly random and not representative !
7629/// let result = hub.users().labels_update(req, "userId", "id")
7630///              .doit().await;
7631/// # }
7632/// ```
7633pub struct UserLabelUpdateCall<'a, C>
7634where
7635    C: 'a,
7636{
7637    hub: &'a Gmail<C>,
7638    _request: Label,
7639    _user_id: String,
7640    _id: String,
7641    _delegate: Option<&'a mut dyn common::Delegate>,
7642    _additional_params: HashMap<String, String>,
7643    _scopes: BTreeSet<String>,
7644}
7645
7646impl<'a, C> common::CallBuilder for UserLabelUpdateCall<'a, C> {}
7647
7648impl<'a, C> UserLabelUpdateCall<'a, C>
7649where
7650    C: common::Connector,
7651{
7652    /// Perform the operation you have build so far.
7653    pub async fn doit(mut self) -> common::Result<(common::Response, Label)> {
7654        use std::borrow::Cow;
7655        use std::io::{Read, Seek};
7656
7657        use common::{url::Params, ToParts};
7658        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
7659
7660        let mut dd = common::DefaultDelegate;
7661        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
7662        dlg.begin(common::MethodInfo {
7663            id: "gmail.users.labels.update",
7664            http_method: hyper::Method::PUT,
7665        });
7666
7667        for &field in ["alt", "userId", "id"].iter() {
7668            if self._additional_params.contains_key(field) {
7669                dlg.finished(false);
7670                return Err(common::Error::FieldClash(field));
7671            }
7672        }
7673
7674        let mut params = Params::with_capacity(5 + self._additional_params.len());
7675        params.push("userId", self._user_id);
7676        params.push("id", self._id);
7677
7678        params.extend(self._additional_params.iter());
7679
7680        params.push("alt", "json");
7681        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/labels/{id}";
7682        if self._scopes.is_empty() {
7683            self._scopes.insert(Scope::Gmai.as_ref().to_string());
7684        }
7685
7686        #[allow(clippy::single_element_loop)]
7687        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
7688            url = params.uri_replacement(url, param_name, find_this, false);
7689        }
7690        {
7691            let to_remove = ["id", "userId"];
7692            params.remove_params(&to_remove);
7693        }
7694
7695        let url = params.parse_with_url(&url);
7696
7697        let mut json_mime_type = mime::APPLICATION_JSON;
7698        let mut request_value_reader = {
7699            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
7700            common::remove_json_null_values(&mut value);
7701            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
7702            serde_json::to_writer(&mut dst, &value).unwrap();
7703            dst
7704        };
7705        let request_size = request_value_reader
7706            .seek(std::io::SeekFrom::End(0))
7707            .unwrap();
7708        request_value_reader
7709            .seek(std::io::SeekFrom::Start(0))
7710            .unwrap();
7711
7712        loop {
7713            let token = match self
7714                .hub
7715                .auth
7716                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
7717                .await
7718            {
7719                Ok(token) => token,
7720                Err(e) => match dlg.token(e) {
7721                    Ok(token) => token,
7722                    Err(e) => {
7723                        dlg.finished(false);
7724                        return Err(common::Error::MissingToken(e));
7725                    }
7726                },
7727            };
7728            request_value_reader
7729                .seek(std::io::SeekFrom::Start(0))
7730                .unwrap();
7731            let mut req_result = {
7732                let client = &self.hub.client;
7733                dlg.pre_request();
7734                let mut req_builder = hyper::Request::builder()
7735                    .method(hyper::Method::PUT)
7736                    .uri(url.as_str())
7737                    .header(USER_AGENT, self.hub._user_agent.clone());
7738
7739                if let Some(token) = token.as_ref() {
7740                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
7741                }
7742
7743                let request = req_builder
7744                    .header(CONTENT_TYPE, json_mime_type.to_string())
7745                    .header(CONTENT_LENGTH, request_size as u64)
7746                    .body(common::to_body(
7747                        request_value_reader.get_ref().clone().into(),
7748                    ));
7749
7750                client.request(request.unwrap()).await
7751            };
7752
7753            match req_result {
7754                Err(err) => {
7755                    if let common::Retry::After(d) = dlg.http_error(&err) {
7756                        sleep(d).await;
7757                        continue;
7758                    }
7759                    dlg.finished(false);
7760                    return Err(common::Error::HttpError(err));
7761                }
7762                Ok(res) => {
7763                    let (mut parts, body) = res.into_parts();
7764                    let mut body = common::Body::new(body);
7765                    if !parts.status.is_success() {
7766                        let bytes = common::to_bytes(body).await.unwrap_or_default();
7767                        let error = serde_json::from_str(&common::to_string(&bytes));
7768                        let response = common::to_response(parts, bytes.into());
7769
7770                        if let common::Retry::After(d) =
7771                            dlg.http_failure(&response, error.as_ref().ok())
7772                        {
7773                            sleep(d).await;
7774                            continue;
7775                        }
7776
7777                        dlg.finished(false);
7778
7779                        return Err(match error {
7780                            Ok(value) => common::Error::BadRequest(value),
7781                            _ => common::Error::Failure(response),
7782                        });
7783                    }
7784                    let response = {
7785                        let bytes = common::to_bytes(body).await.unwrap_or_default();
7786                        let encoded = common::to_string(&bytes);
7787                        match serde_json::from_str(&encoded) {
7788                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
7789                            Err(error) => {
7790                                dlg.response_json_decode_error(&encoded, &error);
7791                                return Err(common::Error::JsonDecodeError(
7792                                    encoded.to_string(),
7793                                    error,
7794                                ));
7795                            }
7796                        }
7797                    };
7798
7799                    dlg.finished(true);
7800                    return Ok(response);
7801                }
7802            }
7803        }
7804    }
7805
7806    ///
7807    /// Sets the *request* property to the given value.
7808    ///
7809    /// Even though the property as already been set when instantiating this call,
7810    /// we provide this method for API completeness.
7811    pub fn request(mut self, new_value: Label) -> UserLabelUpdateCall<'a, C> {
7812        self._request = new_value;
7813        self
7814    }
7815    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
7816    ///
7817    /// Sets the *user id* path property to the given value.
7818    ///
7819    /// Even though the property as already been set when instantiating this call,
7820    /// we provide this method for API completeness.
7821    pub fn user_id(mut self, new_value: &str) -> UserLabelUpdateCall<'a, C> {
7822        self._user_id = new_value.to_string();
7823        self
7824    }
7825    /// The ID of the label to update.
7826    ///
7827    /// Sets the *id* path property to the given value.
7828    ///
7829    /// Even though the property as already been set when instantiating this call,
7830    /// we provide this method for API completeness.
7831    pub fn id(mut self, new_value: &str) -> UserLabelUpdateCall<'a, C> {
7832        self._id = new_value.to_string();
7833        self
7834    }
7835    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
7836    /// while executing the actual API request.
7837    ///
7838    /// ````text
7839    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
7840    /// ````
7841    ///
7842    /// Sets the *delegate* property to the given value.
7843    pub fn delegate(
7844        mut self,
7845        new_value: &'a mut dyn common::Delegate,
7846    ) -> UserLabelUpdateCall<'a, C> {
7847        self._delegate = Some(new_value);
7848        self
7849    }
7850
7851    /// Set any additional parameter of the query string used in the request.
7852    /// It should be used to set parameters which are not yet available through their own
7853    /// setters.
7854    ///
7855    /// Please note that this method must not be used to set any of the known parameters
7856    /// which have their own setter method. If done anyway, the request will fail.
7857    ///
7858    /// # Additional Parameters
7859    ///
7860    /// * *$.xgafv* (query-string) - V1 error format.
7861    /// * *access_token* (query-string) - OAuth access token.
7862    /// * *alt* (query-string) - Data format for response.
7863    /// * *callback* (query-string) - JSONP
7864    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
7865    /// * *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.
7866    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
7867    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
7868    /// * *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.
7869    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
7870    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
7871    pub fn param<T>(mut self, name: T, value: T) -> UserLabelUpdateCall<'a, C>
7872    where
7873        T: AsRef<str>,
7874    {
7875        self._additional_params
7876            .insert(name.as_ref().to_string(), value.as_ref().to_string());
7877        self
7878    }
7879
7880    /// Identifies the authorization scope for the method you are building.
7881    ///
7882    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
7883    /// [`Scope::Gmai`].
7884    ///
7885    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
7886    /// tokens for more than one scope.
7887    ///
7888    /// Usually there is more than one suitable scope to authorize an operation, some of which may
7889    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
7890    /// sufficient, a read-write scope will do as well.
7891    pub fn add_scope<St>(mut self, scope: St) -> UserLabelUpdateCall<'a, C>
7892    where
7893        St: AsRef<str>,
7894    {
7895        self._scopes.insert(String::from(scope.as_ref()));
7896        self
7897    }
7898    /// Identifies the authorization scope(s) for the method you are building.
7899    ///
7900    /// See [`Self::add_scope()`] for details.
7901    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserLabelUpdateCall<'a, C>
7902    where
7903        I: IntoIterator<Item = St>,
7904        St: AsRef<str>,
7905    {
7906        self._scopes
7907            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
7908        self
7909    }
7910
7911    /// Removes all scopes, and no default scope will be used either.
7912    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
7913    /// for details).
7914    pub fn clear_scopes(mut self) -> UserLabelUpdateCall<'a, C> {
7915        self._scopes.clear();
7916        self
7917    }
7918}
7919
7920/// Gets the specified message attachment.
7921///
7922/// A builder for the *messages.attachments.get* method supported by a *user* resource.
7923/// It is not used directly, but through a [`UserMethods`] instance.
7924///
7925/// # Example
7926///
7927/// Instantiate a resource method builder
7928///
7929/// ```test_harness,no_run
7930/// # extern crate hyper;
7931/// # extern crate hyper_rustls;
7932/// # extern crate google_gmail1 as gmail1;
7933/// # async fn dox() {
7934/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
7935///
7936/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
7937/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
7938/// #     secret,
7939/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
7940/// # ).build().await.unwrap();
7941///
7942/// # let client = hyper_util::client::legacy::Client::builder(
7943/// #     hyper_util::rt::TokioExecutor::new()
7944/// # )
7945/// # .build(
7946/// #     hyper_rustls::HttpsConnectorBuilder::new()
7947/// #         .with_native_roots()
7948/// #         .unwrap()
7949/// #         .https_or_http()
7950/// #         .enable_http1()
7951/// #         .build()
7952/// # );
7953/// # let mut hub = Gmail::new(client, auth);
7954/// // You can configure optional parameters by calling the respective setters at will, and
7955/// // execute the final call using `doit()`.
7956/// // Values shown here are possibly random and not representative !
7957/// let result = hub.users().messages_attachments_get("userId", "messageId", "id")
7958///              .doit().await;
7959/// # }
7960/// ```
7961pub struct UserMessageAttachmentGetCall<'a, C>
7962where
7963    C: 'a,
7964{
7965    hub: &'a Gmail<C>,
7966    _user_id: String,
7967    _message_id: String,
7968    _id: String,
7969    _delegate: Option<&'a mut dyn common::Delegate>,
7970    _additional_params: HashMap<String, String>,
7971    _scopes: BTreeSet<String>,
7972}
7973
7974impl<'a, C> common::CallBuilder for UserMessageAttachmentGetCall<'a, C> {}
7975
7976impl<'a, C> UserMessageAttachmentGetCall<'a, C>
7977where
7978    C: common::Connector,
7979{
7980    /// Perform the operation you have build so far.
7981    pub async fn doit(mut self) -> common::Result<(common::Response, MessagePartBody)> {
7982        use std::borrow::Cow;
7983        use std::io::{Read, Seek};
7984
7985        use common::{url::Params, ToParts};
7986        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
7987
7988        let mut dd = common::DefaultDelegate;
7989        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
7990        dlg.begin(common::MethodInfo {
7991            id: "gmail.users.messages.attachments.get",
7992            http_method: hyper::Method::GET,
7993        });
7994
7995        for &field in ["alt", "userId", "messageId", "id"].iter() {
7996            if self._additional_params.contains_key(field) {
7997                dlg.finished(false);
7998                return Err(common::Error::FieldClash(field));
7999            }
8000        }
8001
8002        let mut params = Params::with_capacity(5 + self._additional_params.len());
8003        params.push("userId", self._user_id);
8004        params.push("messageId", self._message_id);
8005        params.push("id", self._id);
8006
8007        params.extend(self._additional_params.iter());
8008
8009        params.push("alt", "json");
8010        let mut url = self.hub._base_url.clone()
8011            + "gmail/v1/users/{userId}/messages/{messageId}/attachments/{id}";
8012        if self._scopes.is_empty() {
8013            self._scopes
8014                .insert(Scope::AddonCurrentMessageReadonly.as_ref().to_string());
8015        }
8016
8017        #[allow(clippy::single_element_loop)]
8018        for &(find_this, param_name) in [
8019            ("{userId}", "userId"),
8020            ("{messageId}", "messageId"),
8021            ("{id}", "id"),
8022        ]
8023        .iter()
8024        {
8025            url = params.uri_replacement(url, param_name, find_this, false);
8026        }
8027        {
8028            let to_remove = ["id", "messageId", "userId"];
8029            params.remove_params(&to_remove);
8030        }
8031
8032        let url = params.parse_with_url(&url);
8033
8034        loop {
8035            let token = match self
8036                .hub
8037                .auth
8038                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
8039                .await
8040            {
8041                Ok(token) => token,
8042                Err(e) => match dlg.token(e) {
8043                    Ok(token) => token,
8044                    Err(e) => {
8045                        dlg.finished(false);
8046                        return Err(common::Error::MissingToken(e));
8047                    }
8048                },
8049            };
8050            let mut req_result = {
8051                let client = &self.hub.client;
8052                dlg.pre_request();
8053                let mut req_builder = hyper::Request::builder()
8054                    .method(hyper::Method::GET)
8055                    .uri(url.as_str())
8056                    .header(USER_AGENT, self.hub._user_agent.clone());
8057
8058                if let Some(token) = token.as_ref() {
8059                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
8060                }
8061
8062                let request = req_builder
8063                    .header(CONTENT_LENGTH, 0_u64)
8064                    .body(common::to_body::<String>(None));
8065
8066                client.request(request.unwrap()).await
8067            };
8068
8069            match req_result {
8070                Err(err) => {
8071                    if let common::Retry::After(d) = dlg.http_error(&err) {
8072                        sleep(d).await;
8073                        continue;
8074                    }
8075                    dlg.finished(false);
8076                    return Err(common::Error::HttpError(err));
8077                }
8078                Ok(res) => {
8079                    let (mut parts, body) = res.into_parts();
8080                    let mut body = common::Body::new(body);
8081                    if !parts.status.is_success() {
8082                        let bytes = common::to_bytes(body).await.unwrap_or_default();
8083                        let error = serde_json::from_str(&common::to_string(&bytes));
8084                        let response = common::to_response(parts, bytes.into());
8085
8086                        if let common::Retry::After(d) =
8087                            dlg.http_failure(&response, error.as_ref().ok())
8088                        {
8089                            sleep(d).await;
8090                            continue;
8091                        }
8092
8093                        dlg.finished(false);
8094
8095                        return Err(match error {
8096                            Ok(value) => common::Error::BadRequest(value),
8097                            _ => common::Error::Failure(response),
8098                        });
8099                    }
8100                    let response = {
8101                        let bytes = common::to_bytes(body).await.unwrap_or_default();
8102                        let encoded = common::to_string(&bytes);
8103                        match serde_json::from_str(&encoded) {
8104                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
8105                            Err(error) => {
8106                                dlg.response_json_decode_error(&encoded, &error);
8107                                return Err(common::Error::JsonDecodeError(
8108                                    encoded.to_string(),
8109                                    error,
8110                                ));
8111                            }
8112                        }
8113                    };
8114
8115                    dlg.finished(true);
8116                    return Ok(response);
8117                }
8118            }
8119        }
8120    }
8121
8122    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
8123    ///
8124    /// Sets the *user id* path property to the given value.
8125    ///
8126    /// Even though the property as already been set when instantiating this call,
8127    /// we provide this method for API completeness.
8128    pub fn user_id(mut self, new_value: &str) -> UserMessageAttachmentGetCall<'a, C> {
8129        self._user_id = new_value.to_string();
8130        self
8131    }
8132    /// The ID of the message containing the attachment.
8133    ///
8134    /// Sets the *message id* path property to the given value.
8135    ///
8136    /// Even though the property as already been set when instantiating this call,
8137    /// we provide this method for API completeness.
8138    pub fn message_id(mut self, new_value: &str) -> UserMessageAttachmentGetCall<'a, C> {
8139        self._message_id = new_value.to_string();
8140        self
8141    }
8142    /// The ID of the attachment.
8143    ///
8144    /// Sets the *id* path property to the given value.
8145    ///
8146    /// Even though the property as already been set when instantiating this call,
8147    /// we provide this method for API completeness.
8148    pub fn id(mut self, new_value: &str) -> UserMessageAttachmentGetCall<'a, C> {
8149        self._id = new_value.to_string();
8150        self
8151    }
8152    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
8153    /// while executing the actual API request.
8154    ///
8155    /// ````text
8156    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
8157    /// ````
8158    ///
8159    /// Sets the *delegate* property to the given value.
8160    pub fn delegate(
8161        mut self,
8162        new_value: &'a mut dyn common::Delegate,
8163    ) -> UserMessageAttachmentGetCall<'a, C> {
8164        self._delegate = Some(new_value);
8165        self
8166    }
8167
8168    /// Set any additional parameter of the query string used in the request.
8169    /// It should be used to set parameters which are not yet available through their own
8170    /// setters.
8171    ///
8172    /// Please note that this method must not be used to set any of the known parameters
8173    /// which have their own setter method. If done anyway, the request will fail.
8174    ///
8175    /// # Additional Parameters
8176    ///
8177    /// * *$.xgafv* (query-string) - V1 error format.
8178    /// * *access_token* (query-string) - OAuth access token.
8179    /// * *alt* (query-string) - Data format for response.
8180    /// * *callback* (query-string) - JSONP
8181    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
8182    /// * *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.
8183    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
8184    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
8185    /// * *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.
8186    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
8187    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
8188    pub fn param<T>(mut self, name: T, value: T) -> UserMessageAttachmentGetCall<'a, C>
8189    where
8190        T: AsRef<str>,
8191    {
8192        self._additional_params
8193            .insert(name.as_ref().to_string(), value.as_ref().to_string());
8194        self
8195    }
8196
8197    /// Identifies the authorization scope for the method you are building.
8198    ///
8199    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
8200    /// [`Scope::AddonCurrentMessageReadonly`].
8201    ///
8202    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
8203    /// tokens for more than one scope.
8204    ///
8205    /// Usually there is more than one suitable scope to authorize an operation, some of which may
8206    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
8207    /// sufficient, a read-write scope will do as well.
8208    pub fn add_scope<St>(mut self, scope: St) -> UserMessageAttachmentGetCall<'a, C>
8209    where
8210        St: AsRef<str>,
8211    {
8212        self._scopes.insert(String::from(scope.as_ref()));
8213        self
8214    }
8215    /// Identifies the authorization scope(s) for the method you are building.
8216    ///
8217    /// See [`Self::add_scope()`] for details.
8218    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserMessageAttachmentGetCall<'a, C>
8219    where
8220        I: IntoIterator<Item = St>,
8221        St: AsRef<str>,
8222    {
8223        self._scopes
8224            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
8225        self
8226    }
8227
8228    /// Removes all scopes, and no default scope will be used either.
8229    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
8230    /// for details).
8231    pub fn clear_scopes(mut self) -> UserMessageAttachmentGetCall<'a, C> {
8232        self._scopes.clear();
8233        self
8234    }
8235}
8236
8237/// Deletes many messages by message ID. Provides no guarantees that messages were not already deleted or even existed at all.
8238///
8239/// A builder for the *messages.batchDelete* method supported by a *user* resource.
8240/// It is not used directly, but through a [`UserMethods`] instance.
8241///
8242/// # Example
8243///
8244/// Instantiate a resource method builder
8245///
8246/// ```test_harness,no_run
8247/// # extern crate hyper;
8248/// # extern crate hyper_rustls;
8249/// # extern crate google_gmail1 as gmail1;
8250/// use gmail1::api::BatchDeleteMessagesRequest;
8251/// # async fn dox() {
8252/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
8253///
8254/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
8255/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
8256/// #     secret,
8257/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
8258/// # ).build().await.unwrap();
8259///
8260/// # let client = hyper_util::client::legacy::Client::builder(
8261/// #     hyper_util::rt::TokioExecutor::new()
8262/// # )
8263/// # .build(
8264/// #     hyper_rustls::HttpsConnectorBuilder::new()
8265/// #         .with_native_roots()
8266/// #         .unwrap()
8267/// #         .https_or_http()
8268/// #         .enable_http1()
8269/// #         .build()
8270/// # );
8271/// # let mut hub = Gmail::new(client, auth);
8272/// // As the method needs a request, you would usually fill it with the desired information
8273/// // into the respective structure. Some of the parts shown here might not be applicable !
8274/// // Values shown here are possibly random and not representative !
8275/// let mut req = BatchDeleteMessagesRequest::default();
8276///
8277/// // You can configure optional parameters by calling the respective setters at will, and
8278/// // execute the final call using `doit()`.
8279/// // Values shown here are possibly random and not representative !
8280/// let result = hub.users().messages_batch_delete(req, "userId")
8281///              .doit().await;
8282/// # }
8283/// ```
8284pub struct UserMessageBatchDeleteCall<'a, C>
8285where
8286    C: 'a,
8287{
8288    hub: &'a Gmail<C>,
8289    _request: BatchDeleteMessagesRequest,
8290    _user_id: String,
8291    _delegate: Option<&'a mut dyn common::Delegate>,
8292    _additional_params: HashMap<String, String>,
8293    _scopes: BTreeSet<String>,
8294}
8295
8296impl<'a, C> common::CallBuilder for UserMessageBatchDeleteCall<'a, C> {}
8297
8298impl<'a, C> UserMessageBatchDeleteCall<'a, C>
8299where
8300    C: common::Connector,
8301{
8302    /// Perform the operation you have build so far.
8303    pub async fn doit(mut self) -> common::Result<common::Response> {
8304        use std::borrow::Cow;
8305        use std::io::{Read, Seek};
8306
8307        use common::{url::Params, ToParts};
8308        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
8309
8310        let mut dd = common::DefaultDelegate;
8311        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
8312        dlg.begin(common::MethodInfo {
8313            id: "gmail.users.messages.batchDelete",
8314            http_method: hyper::Method::POST,
8315        });
8316
8317        for &field in ["userId"].iter() {
8318            if self._additional_params.contains_key(field) {
8319                dlg.finished(false);
8320                return Err(common::Error::FieldClash(field));
8321            }
8322        }
8323
8324        let mut params = Params::with_capacity(3 + self._additional_params.len());
8325        params.push("userId", self._user_id);
8326
8327        params.extend(self._additional_params.iter());
8328
8329        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/messages/batchDelete";
8330        if self._scopes.is_empty() {
8331            self._scopes.insert(Scope::Gmai.as_ref().to_string());
8332        }
8333
8334        #[allow(clippy::single_element_loop)]
8335        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
8336            url = params.uri_replacement(url, param_name, find_this, false);
8337        }
8338        {
8339            let to_remove = ["userId"];
8340            params.remove_params(&to_remove);
8341        }
8342
8343        let url = params.parse_with_url(&url);
8344
8345        let mut json_mime_type = mime::APPLICATION_JSON;
8346        let mut request_value_reader = {
8347            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
8348            common::remove_json_null_values(&mut value);
8349            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
8350            serde_json::to_writer(&mut dst, &value).unwrap();
8351            dst
8352        };
8353        let request_size = request_value_reader
8354            .seek(std::io::SeekFrom::End(0))
8355            .unwrap();
8356        request_value_reader
8357            .seek(std::io::SeekFrom::Start(0))
8358            .unwrap();
8359
8360        loop {
8361            let token = match self
8362                .hub
8363                .auth
8364                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
8365                .await
8366            {
8367                Ok(token) => token,
8368                Err(e) => match dlg.token(e) {
8369                    Ok(token) => token,
8370                    Err(e) => {
8371                        dlg.finished(false);
8372                        return Err(common::Error::MissingToken(e));
8373                    }
8374                },
8375            };
8376            request_value_reader
8377                .seek(std::io::SeekFrom::Start(0))
8378                .unwrap();
8379            let mut req_result = {
8380                let client = &self.hub.client;
8381                dlg.pre_request();
8382                let mut req_builder = hyper::Request::builder()
8383                    .method(hyper::Method::POST)
8384                    .uri(url.as_str())
8385                    .header(USER_AGENT, self.hub._user_agent.clone());
8386
8387                if let Some(token) = token.as_ref() {
8388                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
8389                }
8390
8391                let request = req_builder
8392                    .header(CONTENT_TYPE, json_mime_type.to_string())
8393                    .header(CONTENT_LENGTH, request_size as u64)
8394                    .body(common::to_body(
8395                        request_value_reader.get_ref().clone().into(),
8396                    ));
8397
8398                client.request(request.unwrap()).await
8399            };
8400
8401            match req_result {
8402                Err(err) => {
8403                    if let common::Retry::After(d) = dlg.http_error(&err) {
8404                        sleep(d).await;
8405                        continue;
8406                    }
8407                    dlg.finished(false);
8408                    return Err(common::Error::HttpError(err));
8409                }
8410                Ok(res) => {
8411                    let (mut parts, body) = res.into_parts();
8412                    let mut body = common::Body::new(body);
8413                    if !parts.status.is_success() {
8414                        let bytes = common::to_bytes(body).await.unwrap_or_default();
8415                        let error = serde_json::from_str(&common::to_string(&bytes));
8416                        let response = common::to_response(parts, bytes.into());
8417
8418                        if let common::Retry::After(d) =
8419                            dlg.http_failure(&response, error.as_ref().ok())
8420                        {
8421                            sleep(d).await;
8422                            continue;
8423                        }
8424
8425                        dlg.finished(false);
8426
8427                        return Err(match error {
8428                            Ok(value) => common::Error::BadRequest(value),
8429                            _ => common::Error::Failure(response),
8430                        });
8431                    }
8432                    let response = common::Response::from_parts(parts, body);
8433
8434                    dlg.finished(true);
8435                    return Ok(response);
8436                }
8437            }
8438        }
8439    }
8440
8441    ///
8442    /// Sets the *request* property to the given value.
8443    ///
8444    /// Even though the property as already been set when instantiating this call,
8445    /// we provide this method for API completeness.
8446    pub fn request(
8447        mut self,
8448        new_value: BatchDeleteMessagesRequest,
8449    ) -> UserMessageBatchDeleteCall<'a, C> {
8450        self._request = new_value;
8451        self
8452    }
8453    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
8454    ///
8455    /// Sets the *user id* path property to the given value.
8456    ///
8457    /// Even though the property as already been set when instantiating this call,
8458    /// we provide this method for API completeness.
8459    pub fn user_id(mut self, new_value: &str) -> UserMessageBatchDeleteCall<'a, C> {
8460        self._user_id = new_value.to_string();
8461        self
8462    }
8463    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
8464    /// while executing the actual API request.
8465    ///
8466    /// ````text
8467    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
8468    /// ````
8469    ///
8470    /// Sets the *delegate* property to the given value.
8471    pub fn delegate(
8472        mut self,
8473        new_value: &'a mut dyn common::Delegate,
8474    ) -> UserMessageBatchDeleteCall<'a, C> {
8475        self._delegate = Some(new_value);
8476        self
8477    }
8478
8479    /// Set any additional parameter of the query string used in the request.
8480    /// It should be used to set parameters which are not yet available through their own
8481    /// setters.
8482    ///
8483    /// Please note that this method must not be used to set any of the known parameters
8484    /// which have their own setter method. If done anyway, the request will fail.
8485    ///
8486    /// # Additional Parameters
8487    ///
8488    /// * *$.xgafv* (query-string) - V1 error format.
8489    /// * *access_token* (query-string) - OAuth access token.
8490    /// * *alt* (query-string) - Data format for response.
8491    /// * *callback* (query-string) - JSONP
8492    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
8493    /// * *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.
8494    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
8495    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
8496    /// * *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.
8497    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
8498    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
8499    pub fn param<T>(mut self, name: T, value: T) -> UserMessageBatchDeleteCall<'a, C>
8500    where
8501        T: AsRef<str>,
8502    {
8503        self._additional_params
8504            .insert(name.as_ref().to_string(), value.as_ref().to_string());
8505        self
8506    }
8507
8508    /// Identifies the authorization scope for the method you are building.
8509    ///
8510    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
8511    /// [`Scope::Gmai`].
8512    ///
8513    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
8514    /// tokens for more than one scope.
8515    ///
8516    /// Usually there is more than one suitable scope to authorize an operation, some of which may
8517    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
8518    /// sufficient, a read-write scope will do as well.
8519    pub fn add_scope<St>(mut self, scope: St) -> UserMessageBatchDeleteCall<'a, C>
8520    where
8521        St: AsRef<str>,
8522    {
8523        self._scopes.insert(String::from(scope.as_ref()));
8524        self
8525    }
8526    /// Identifies the authorization scope(s) for the method you are building.
8527    ///
8528    /// See [`Self::add_scope()`] for details.
8529    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserMessageBatchDeleteCall<'a, C>
8530    where
8531        I: IntoIterator<Item = St>,
8532        St: AsRef<str>,
8533    {
8534        self._scopes
8535            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
8536        self
8537    }
8538
8539    /// Removes all scopes, and no default scope will be used either.
8540    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
8541    /// for details).
8542    pub fn clear_scopes(mut self) -> UserMessageBatchDeleteCall<'a, C> {
8543        self._scopes.clear();
8544        self
8545    }
8546}
8547
8548/// Modifies the labels on the specified messages.
8549///
8550/// A builder for the *messages.batchModify* method supported by a *user* resource.
8551/// It is not used directly, but through a [`UserMethods`] instance.
8552///
8553/// # Example
8554///
8555/// Instantiate a resource method builder
8556///
8557/// ```test_harness,no_run
8558/// # extern crate hyper;
8559/// # extern crate hyper_rustls;
8560/// # extern crate google_gmail1 as gmail1;
8561/// use gmail1::api::BatchModifyMessagesRequest;
8562/// # async fn dox() {
8563/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
8564///
8565/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
8566/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
8567/// #     secret,
8568/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
8569/// # ).build().await.unwrap();
8570///
8571/// # let client = hyper_util::client::legacy::Client::builder(
8572/// #     hyper_util::rt::TokioExecutor::new()
8573/// # )
8574/// # .build(
8575/// #     hyper_rustls::HttpsConnectorBuilder::new()
8576/// #         .with_native_roots()
8577/// #         .unwrap()
8578/// #         .https_or_http()
8579/// #         .enable_http1()
8580/// #         .build()
8581/// # );
8582/// # let mut hub = Gmail::new(client, auth);
8583/// // As the method needs a request, you would usually fill it with the desired information
8584/// // into the respective structure. Some of the parts shown here might not be applicable !
8585/// // Values shown here are possibly random and not representative !
8586/// let mut req = BatchModifyMessagesRequest::default();
8587///
8588/// // You can configure optional parameters by calling the respective setters at will, and
8589/// // execute the final call using `doit()`.
8590/// // Values shown here are possibly random and not representative !
8591/// let result = hub.users().messages_batch_modify(req, "userId")
8592///              .doit().await;
8593/// # }
8594/// ```
8595pub struct UserMessageBatchModifyCall<'a, C>
8596where
8597    C: 'a,
8598{
8599    hub: &'a Gmail<C>,
8600    _request: BatchModifyMessagesRequest,
8601    _user_id: String,
8602    _delegate: Option<&'a mut dyn common::Delegate>,
8603    _additional_params: HashMap<String, String>,
8604    _scopes: BTreeSet<String>,
8605}
8606
8607impl<'a, C> common::CallBuilder for UserMessageBatchModifyCall<'a, C> {}
8608
8609impl<'a, C> UserMessageBatchModifyCall<'a, C>
8610where
8611    C: common::Connector,
8612{
8613    /// Perform the operation you have build so far.
8614    pub async fn doit(mut self) -> common::Result<common::Response> {
8615        use std::borrow::Cow;
8616        use std::io::{Read, Seek};
8617
8618        use common::{url::Params, ToParts};
8619        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
8620
8621        let mut dd = common::DefaultDelegate;
8622        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
8623        dlg.begin(common::MethodInfo {
8624            id: "gmail.users.messages.batchModify",
8625            http_method: hyper::Method::POST,
8626        });
8627
8628        for &field in ["userId"].iter() {
8629            if self._additional_params.contains_key(field) {
8630                dlg.finished(false);
8631                return Err(common::Error::FieldClash(field));
8632            }
8633        }
8634
8635        let mut params = Params::with_capacity(3 + self._additional_params.len());
8636        params.push("userId", self._user_id);
8637
8638        params.extend(self._additional_params.iter());
8639
8640        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/messages/batchModify";
8641        if self._scopes.is_empty() {
8642            self._scopes.insert(Scope::Gmai.as_ref().to_string());
8643        }
8644
8645        #[allow(clippy::single_element_loop)]
8646        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
8647            url = params.uri_replacement(url, param_name, find_this, false);
8648        }
8649        {
8650            let to_remove = ["userId"];
8651            params.remove_params(&to_remove);
8652        }
8653
8654        let url = params.parse_with_url(&url);
8655
8656        let mut json_mime_type = mime::APPLICATION_JSON;
8657        let mut request_value_reader = {
8658            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
8659            common::remove_json_null_values(&mut value);
8660            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
8661            serde_json::to_writer(&mut dst, &value).unwrap();
8662            dst
8663        };
8664        let request_size = request_value_reader
8665            .seek(std::io::SeekFrom::End(0))
8666            .unwrap();
8667        request_value_reader
8668            .seek(std::io::SeekFrom::Start(0))
8669            .unwrap();
8670
8671        loop {
8672            let token = match self
8673                .hub
8674                .auth
8675                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
8676                .await
8677            {
8678                Ok(token) => token,
8679                Err(e) => match dlg.token(e) {
8680                    Ok(token) => token,
8681                    Err(e) => {
8682                        dlg.finished(false);
8683                        return Err(common::Error::MissingToken(e));
8684                    }
8685                },
8686            };
8687            request_value_reader
8688                .seek(std::io::SeekFrom::Start(0))
8689                .unwrap();
8690            let mut req_result = {
8691                let client = &self.hub.client;
8692                dlg.pre_request();
8693                let mut req_builder = hyper::Request::builder()
8694                    .method(hyper::Method::POST)
8695                    .uri(url.as_str())
8696                    .header(USER_AGENT, self.hub._user_agent.clone());
8697
8698                if let Some(token) = token.as_ref() {
8699                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
8700                }
8701
8702                let request = req_builder
8703                    .header(CONTENT_TYPE, json_mime_type.to_string())
8704                    .header(CONTENT_LENGTH, request_size as u64)
8705                    .body(common::to_body(
8706                        request_value_reader.get_ref().clone().into(),
8707                    ));
8708
8709                client.request(request.unwrap()).await
8710            };
8711
8712            match req_result {
8713                Err(err) => {
8714                    if let common::Retry::After(d) = dlg.http_error(&err) {
8715                        sleep(d).await;
8716                        continue;
8717                    }
8718                    dlg.finished(false);
8719                    return Err(common::Error::HttpError(err));
8720                }
8721                Ok(res) => {
8722                    let (mut parts, body) = res.into_parts();
8723                    let mut body = common::Body::new(body);
8724                    if !parts.status.is_success() {
8725                        let bytes = common::to_bytes(body).await.unwrap_or_default();
8726                        let error = serde_json::from_str(&common::to_string(&bytes));
8727                        let response = common::to_response(parts, bytes.into());
8728
8729                        if let common::Retry::After(d) =
8730                            dlg.http_failure(&response, error.as_ref().ok())
8731                        {
8732                            sleep(d).await;
8733                            continue;
8734                        }
8735
8736                        dlg.finished(false);
8737
8738                        return Err(match error {
8739                            Ok(value) => common::Error::BadRequest(value),
8740                            _ => common::Error::Failure(response),
8741                        });
8742                    }
8743                    let response = common::Response::from_parts(parts, body);
8744
8745                    dlg.finished(true);
8746                    return Ok(response);
8747                }
8748            }
8749        }
8750    }
8751
8752    ///
8753    /// Sets the *request* property to the given value.
8754    ///
8755    /// Even though the property as already been set when instantiating this call,
8756    /// we provide this method for API completeness.
8757    pub fn request(
8758        mut self,
8759        new_value: BatchModifyMessagesRequest,
8760    ) -> UserMessageBatchModifyCall<'a, C> {
8761        self._request = new_value;
8762        self
8763    }
8764    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
8765    ///
8766    /// Sets the *user id* path property to the given value.
8767    ///
8768    /// Even though the property as already been set when instantiating this call,
8769    /// we provide this method for API completeness.
8770    pub fn user_id(mut self, new_value: &str) -> UserMessageBatchModifyCall<'a, C> {
8771        self._user_id = new_value.to_string();
8772        self
8773    }
8774    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
8775    /// while executing the actual API request.
8776    ///
8777    /// ````text
8778    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
8779    /// ````
8780    ///
8781    /// Sets the *delegate* property to the given value.
8782    pub fn delegate(
8783        mut self,
8784        new_value: &'a mut dyn common::Delegate,
8785    ) -> UserMessageBatchModifyCall<'a, C> {
8786        self._delegate = Some(new_value);
8787        self
8788    }
8789
8790    /// Set any additional parameter of the query string used in the request.
8791    /// It should be used to set parameters which are not yet available through their own
8792    /// setters.
8793    ///
8794    /// Please note that this method must not be used to set any of the known parameters
8795    /// which have their own setter method. If done anyway, the request will fail.
8796    ///
8797    /// # Additional Parameters
8798    ///
8799    /// * *$.xgafv* (query-string) - V1 error format.
8800    /// * *access_token* (query-string) - OAuth access token.
8801    /// * *alt* (query-string) - Data format for response.
8802    /// * *callback* (query-string) - JSONP
8803    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
8804    /// * *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.
8805    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
8806    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
8807    /// * *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.
8808    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
8809    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
8810    pub fn param<T>(mut self, name: T, value: T) -> UserMessageBatchModifyCall<'a, C>
8811    where
8812        T: AsRef<str>,
8813    {
8814        self._additional_params
8815            .insert(name.as_ref().to_string(), value.as_ref().to_string());
8816        self
8817    }
8818
8819    /// Identifies the authorization scope for the method you are building.
8820    ///
8821    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
8822    /// [`Scope::Gmai`].
8823    ///
8824    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
8825    /// tokens for more than one scope.
8826    ///
8827    /// Usually there is more than one suitable scope to authorize an operation, some of which may
8828    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
8829    /// sufficient, a read-write scope will do as well.
8830    pub fn add_scope<St>(mut self, scope: St) -> UserMessageBatchModifyCall<'a, C>
8831    where
8832        St: AsRef<str>,
8833    {
8834        self._scopes.insert(String::from(scope.as_ref()));
8835        self
8836    }
8837    /// Identifies the authorization scope(s) for the method you are building.
8838    ///
8839    /// See [`Self::add_scope()`] for details.
8840    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserMessageBatchModifyCall<'a, C>
8841    where
8842        I: IntoIterator<Item = St>,
8843        St: AsRef<str>,
8844    {
8845        self._scopes
8846            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
8847        self
8848    }
8849
8850    /// Removes all scopes, and no default scope will be used either.
8851    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
8852    /// for details).
8853    pub fn clear_scopes(mut self) -> UserMessageBatchModifyCall<'a, C> {
8854        self._scopes.clear();
8855        self
8856    }
8857}
8858
8859/// Immediately and permanently deletes the specified message. This operation cannot be undone. Prefer `messages.trash` instead.
8860///
8861/// A builder for the *messages.delete* method supported by a *user* resource.
8862/// It is not used directly, but through a [`UserMethods`] instance.
8863///
8864/// # Example
8865///
8866/// Instantiate a resource method builder
8867///
8868/// ```test_harness,no_run
8869/// # extern crate hyper;
8870/// # extern crate hyper_rustls;
8871/// # extern crate google_gmail1 as gmail1;
8872/// # async fn dox() {
8873/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
8874///
8875/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
8876/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
8877/// #     secret,
8878/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
8879/// # ).build().await.unwrap();
8880///
8881/// # let client = hyper_util::client::legacy::Client::builder(
8882/// #     hyper_util::rt::TokioExecutor::new()
8883/// # )
8884/// # .build(
8885/// #     hyper_rustls::HttpsConnectorBuilder::new()
8886/// #         .with_native_roots()
8887/// #         .unwrap()
8888/// #         .https_or_http()
8889/// #         .enable_http1()
8890/// #         .build()
8891/// # );
8892/// # let mut hub = Gmail::new(client, auth);
8893/// // You can configure optional parameters by calling the respective setters at will, and
8894/// // execute the final call using `doit()`.
8895/// // Values shown here are possibly random and not representative !
8896/// let result = hub.users().messages_delete("userId", "id")
8897///              .doit().await;
8898/// # }
8899/// ```
8900pub struct UserMessageDeleteCall<'a, C>
8901where
8902    C: 'a,
8903{
8904    hub: &'a Gmail<C>,
8905    _user_id: String,
8906    _id: String,
8907    _delegate: Option<&'a mut dyn common::Delegate>,
8908    _additional_params: HashMap<String, String>,
8909    _scopes: BTreeSet<String>,
8910}
8911
8912impl<'a, C> common::CallBuilder for UserMessageDeleteCall<'a, C> {}
8913
8914impl<'a, C> UserMessageDeleteCall<'a, C>
8915where
8916    C: common::Connector,
8917{
8918    /// Perform the operation you have build so far.
8919    pub async fn doit(mut self) -> common::Result<common::Response> {
8920        use std::borrow::Cow;
8921        use std::io::{Read, Seek};
8922
8923        use common::{url::Params, ToParts};
8924        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
8925
8926        let mut dd = common::DefaultDelegate;
8927        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
8928        dlg.begin(common::MethodInfo {
8929            id: "gmail.users.messages.delete",
8930            http_method: hyper::Method::DELETE,
8931        });
8932
8933        for &field in ["userId", "id"].iter() {
8934            if self._additional_params.contains_key(field) {
8935                dlg.finished(false);
8936                return Err(common::Error::FieldClash(field));
8937            }
8938        }
8939
8940        let mut params = Params::with_capacity(3 + self._additional_params.len());
8941        params.push("userId", self._user_id);
8942        params.push("id", self._id);
8943
8944        params.extend(self._additional_params.iter());
8945
8946        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/messages/{id}";
8947        if self._scopes.is_empty() {
8948            self._scopes.insert(Scope::Gmai.as_ref().to_string());
8949        }
8950
8951        #[allow(clippy::single_element_loop)]
8952        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
8953            url = params.uri_replacement(url, param_name, find_this, false);
8954        }
8955        {
8956            let to_remove = ["id", "userId"];
8957            params.remove_params(&to_remove);
8958        }
8959
8960        let url = params.parse_with_url(&url);
8961
8962        loop {
8963            let token = match self
8964                .hub
8965                .auth
8966                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
8967                .await
8968            {
8969                Ok(token) => token,
8970                Err(e) => match dlg.token(e) {
8971                    Ok(token) => token,
8972                    Err(e) => {
8973                        dlg.finished(false);
8974                        return Err(common::Error::MissingToken(e));
8975                    }
8976                },
8977            };
8978            let mut req_result = {
8979                let client = &self.hub.client;
8980                dlg.pre_request();
8981                let mut req_builder = hyper::Request::builder()
8982                    .method(hyper::Method::DELETE)
8983                    .uri(url.as_str())
8984                    .header(USER_AGENT, self.hub._user_agent.clone());
8985
8986                if let Some(token) = token.as_ref() {
8987                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
8988                }
8989
8990                let request = req_builder
8991                    .header(CONTENT_LENGTH, 0_u64)
8992                    .body(common::to_body::<String>(None));
8993
8994                client.request(request.unwrap()).await
8995            };
8996
8997            match req_result {
8998                Err(err) => {
8999                    if let common::Retry::After(d) = dlg.http_error(&err) {
9000                        sleep(d).await;
9001                        continue;
9002                    }
9003                    dlg.finished(false);
9004                    return Err(common::Error::HttpError(err));
9005                }
9006                Ok(res) => {
9007                    let (mut parts, body) = res.into_parts();
9008                    let mut body = common::Body::new(body);
9009                    if !parts.status.is_success() {
9010                        let bytes = common::to_bytes(body).await.unwrap_or_default();
9011                        let error = serde_json::from_str(&common::to_string(&bytes));
9012                        let response = common::to_response(parts, bytes.into());
9013
9014                        if let common::Retry::After(d) =
9015                            dlg.http_failure(&response, error.as_ref().ok())
9016                        {
9017                            sleep(d).await;
9018                            continue;
9019                        }
9020
9021                        dlg.finished(false);
9022
9023                        return Err(match error {
9024                            Ok(value) => common::Error::BadRequest(value),
9025                            _ => common::Error::Failure(response),
9026                        });
9027                    }
9028                    let response = common::Response::from_parts(parts, body);
9029
9030                    dlg.finished(true);
9031                    return Ok(response);
9032                }
9033            }
9034        }
9035    }
9036
9037    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
9038    ///
9039    /// Sets the *user id* path property to the given value.
9040    ///
9041    /// Even though the property as already been set when instantiating this call,
9042    /// we provide this method for API completeness.
9043    pub fn user_id(mut self, new_value: &str) -> UserMessageDeleteCall<'a, C> {
9044        self._user_id = new_value.to_string();
9045        self
9046    }
9047    /// The ID of the message to delete.
9048    ///
9049    /// Sets the *id* path property to the given value.
9050    ///
9051    /// Even though the property as already been set when instantiating this call,
9052    /// we provide this method for API completeness.
9053    pub fn id(mut self, new_value: &str) -> UserMessageDeleteCall<'a, C> {
9054        self._id = new_value.to_string();
9055        self
9056    }
9057    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
9058    /// while executing the actual API request.
9059    ///
9060    /// ````text
9061    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
9062    /// ````
9063    ///
9064    /// Sets the *delegate* property to the given value.
9065    pub fn delegate(
9066        mut self,
9067        new_value: &'a mut dyn common::Delegate,
9068    ) -> UserMessageDeleteCall<'a, C> {
9069        self._delegate = Some(new_value);
9070        self
9071    }
9072
9073    /// Set any additional parameter of the query string used in the request.
9074    /// It should be used to set parameters which are not yet available through their own
9075    /// setters.
9076    ///
9077    /// Please note that this method must not be used to set any of the known parameters
9078    /// which have their own setter method. If done anyway, the request will fail.
9079    ///
9080    /// # Additional Parameters
9081    ///
9082    /// * *$.xgafv* (query-string) - V1 error format.
9083    /// * *access_token* (query-string) - OAuth access token.
9084    /// * *alt* (query-string) - Data format for response.
9085    /// * *callback* (query-string) - JSONP
9086    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
9087    /// * *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.
9088    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
9089    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
9090    /// * *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.
9091    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
9092    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
9093    pub fn param<T>(mut self, name: T, value: T) -> UserMessageDeleteCall<'a, C>
9094    where
9095        T: AsRef<str>,
9096    {
9097        self._additional_params
9098            .insert(name.as_ref().to_string(), value.as_ref().to_string());
9099        self
9100    }
9101
9102    /// Identifies the authorization scope for the method you are building.
9103    ///
9104    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
9105    /// [`Scope::Gmai`].
9106    ///
9107    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
9108    /// tokens for more than one scope.
9109    ///
9110    /// Usually there is more than one suitable scope to authorize an operation, some of which may
9111    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
9112    /// sufficient, a read-write scope will do as well.
9113    pub fn add_scope<St>(mut self, scope: St) -> UserMessageDeleteCall<'a, C>
9114    where
9115        St: AsRef<str>,
9116    {
9117        self._scopes.insert(String::from(scope.as_ref()));
9118        self
9119    }
9120    /// Identifies the authorization scope(s) for the method you are building.
9121    ///
9122    /// See [`Self::add_scope()`] for details.
9123    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserMessageDeleteCall<'a, C>
9124    where
9125        I: IntoIterator<Item = St>,
9126        St: AsRef<str>,
9127    {
9128        self._scopes
9129            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
9130        self
9131    }
9132
9133    /// Removes all scopes, and no default scope will be used either.
9134    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
9135    /// for details).
9136    pub fn clear_scopes(mut self) -> UserMessageDeleteCall<'a, C> {
9137        self._scopes.clear();
9138        self
9139    }
9140}
9141
9142/// Gets the specified message.
9143///
9144/// A builder for the *messages.get* method supported by a *user* resource.
9145/// It is not used directly, but through a [`UserMethods`] instance.
9146///
9147/// # Example
9148///
9149/// Instantiate a resource method builder
9150///
9151/// ```test_harness,no_run
9152/// # extern crate hyper;
9153/// # extern crate hyper_rustls;
9154/// # extern crate google_gmail1 as gmail1;
9155/// # async fn dox() {
9156/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
9157///
9158/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
9159/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
9160/// #     secret,
9161/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
9162/// # ).build().await.unwrap();
9163///
9164/// # let client = hyper_util::client::legacy::Client::builder(
9165/// #     hyper_util::rt::TokioExecutor::new()
9166/// # )
9167/// # .build(
9168/// #     hyper_rustls::HttpsConnectorBuilder::new()
9169/// #         .with_native_roots()
9170/// #         .unwrap()
9171/// #         .https_or_http()
9172/// #         .enable_http1()
9173/// #         .build()
9174/// # );
9175/// # let mut hub = Gmail::new(client, auth);
9176/// // You can configure optional parameters by calling the respective setters at will, and
9177/// // execute the final call using `doit()`.
9178/// // Values shown here are possibly random and not representative !
9179/// let result = hub.users().messages_get("userId", "id")
9180///              .add_metadata_headers("dolor")
9181///              .format("duo")
9182///              .doit().await;
9183/// # }
9184/// ```
9185pub struct UserMessageGetCall<'a, C>
9186where
9187    C: 'a,
9188{
9189    hub: &'a Gmail<C>,
9190    _user_id: String,
9191    _id: String,
9192    _metadata_headers: Vec<String>,
9193    _format: Option<String>,
9194    _delegate: Option<&'a mut dyn common::Delegate>,
9195    _additional_params: HashMap<String, String>,
9196    _scopes: BTreeSet<String>,
9197}
9198
9199impl<'a, C> common::CallBuilder for UserMessageGetCall<'a, C> {}
9200
9201impl<'a, C> UserMessageGetCall<'a, C>
9202where
9203    C: common::Connector,
9204{
9205    /// Perform the operation you have build so far.
9206    pub async fn doit(mut self) -> common::Result<(common::Response, Message)> {
9207        use std::borrow::Cow;
9208        use std::io::{Read, Seek};
9209
9210        use common::{url::Params, ToParts};
9211        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
9212
9213        let mut dd = common::DefaultDelegate;
9214        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
9215        dlg.begin(common::MethodInfo {
9216            id: "gmail.users.messages.get",
9217            http_method: hyper::Method::GET,
9218        });
9219
9220        for &field in ["alt", "userId", "id", "metadataHeaders", "format"].iter() {
9221            if self._additional_params.contains_key(field) {
9222                dlg.finished(false);
9223                return Err(common::Error::FieldClash(field));
9224            }
9225        }
9226
9227        let mut params = Params::with_capacity(6 + self._additional_params.len());
9228        params.push("userId", self._user_id);
9229        params.push("id", self._id);
9230        if !self._metadata_headers.is_empty() {
9231            for f in self._metadata_headers.iter() {
9232                params.push("metadataHeaders", f);
9233            }
9234        }
9235        if let Some(value) = self._format.as_ref() {
9236            params.push("format", value);
9237        }
9238
9239        params.extend(self._additional_params.iter());
9240
9241        params.push("alt", "json");
9242        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/messages/{id}";
9243        if self._scopes.is_empty() {
9244            self._scopes
9245                .insert(Scope::AddonCurrentMessageReadonly.as_ref().to_string());
9246        }
9247
9248        #[allow(clippy::single_element_loop)]
9249        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
9250            url = params.uri_replacement(url, param_name, find_this, false);
9251        }
9252        {
9253            let to_remove = ["id", "userId"];
9254            params.remove_params(&to_remove);
9255        }
9256
9257        let url = params.parse_with_url(&url);
9258
9259        loop {
9260            let token = match self
9261                .hub
9262                .auth
9263                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
9264                .await
9265            {
9266                Ok(token) => token,
9267                Err(e) => match dlg.token(e) {
9268                    Ok(token) => token,
9269                    Err(e) => {
9270                        dlg.finished(false);
9271                        return Err(common::Error::MissingToken(e));
9272                    }
9273                },
9274            };
9275            let mut req_result = {
9276                let client = &self.hub.client;
9277                dlg.pre_request();
9278                let mut req_builder = hyper::Request::builder()
9279                    .method(hyper::Method::GET)
9280                    .uri(url.as_str())
9281                    .header(USER_AGENT, self.hub._user_agent.clone());
9282
9283                if let Some(token) = token.as_ref() {
9284                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
9285                }
9286
9287                let request = req_builder
9288                    .header(CONTENT_LENGTH, 0_u64)
9289                    .body(common::to_body::<String>(None));
9290
9291                client.request(request.unwrap()).await
9292            };
9293
9294            match req_result {
9295                Err(err) => {
9296                    if let common::Retry::After(d) = dlg.http_error(&err) {
9297                        sleep(d).await;
9298                        continue;
9299                    }
9300                    dlg.finished(false);
9301                    return Err(common::Error::HttpError(err));
9302                }
9303                Ok(res) => {
9304                    let (mut parts, body) = res.into_parts();
9305                    let mut body = common::Body::new(body);
9306                    if !parts.status.is_success() {
9307                        let bytes = common::to_bytes(body).await.unwrap_or_default();
9308                        let error = serde_json::from_str(&common::to_string(&bytes));
9309                        let response = common::to_response(parts, bytes.into());
9310
9311                        if let common::Retry::After(d) =
9312                            dlg.http_failure(&response, error.as_ref().ok())
9313                        {
9314                            sleep(d).await;
9315                            continue;
9316                        }
9317
9318                        dlg.finished(false);
9319
9320                        return Err(match error {
9321                            Ok(value) => common::Error::BadRequest(value),
9322                            _ => common::Error::Failure(response),
9323                        });
9324                    }
9325                    let response = {
9326                        let bytes = common::to_bytes(body).await.unwrap_or_default();
9327                        let encoded = common::to_string(&bytes);
9328                        match serde_json::from_str(&encoded) {
9329                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
9330                            Err(error) => {
9331                                dlg.response_json_decode_error(&encoded, &error);
9332                                return Err(common::Error::JsonDecodeError(
9333                                    encoded.to_string(),
9334                                    error,
9335                                ));
9336                            }
9337                        }
9338                    };
9339
9340                    dlg.finished(true);
9341                    return Ok(response);
9342                }
9343            }
9344        }
9345    }
9346
9347    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
9348    ///
9349    /// Sets the *user id* path property to the given value.
9350    ///
9351    /// Even though the property as already been set when instantiating this call,
9352    /// we provide this method for API completeness.
9353    pub fn user_id(mut self, new_value: &str) -> UserMessageGetCall<'a, C> {
9354        self._user_id = new_value.to_string();
9355        self
9356    }
9357    /// The ID of the message to retrieve. This ID is usually retrieved using `messages.list`. The ID is also contained in the result when a message is inserted (`messages.insert`) or imported (`messages.import`).
9358    ///
9359    /// Sets the *id* path property to the given value.
9360    ///
9361    /// Even though the property as already been set when instantiating this call,
9362    /// we provide this method for API completeness.
9363    pub fn id(mut self, new_value: &str) -> UserMessageGetCall<'a, C> {
9364        self._id = new_value.to_string();
9365        self
9366    }
9367    /// When given and format is `METADATA`, only include headers specified.
9368    ///
9369    /// Append the given value to the *metadata headers* query property.
9370    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
9371    pub fn add_metadata_headers(mut self, new_value: &str) -> UserMessageGetCall<'a, C> {
9372        self._metadata_headers.push(new_value.to_string());
9373        self
9374    }
9375    /// The format to return the message in.
9376    ///
9377    /// Sets the *format* query property to the given value.
9378    pub fn format(mut self, new_value: &str) -> UserMessageGetCall<'a, C> {
9379        self._format = Some(new_value.to_string());
9380        self
9381    }
9382    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
9383    /// while executing the actual API request.
9384    ///
9385    /// ````text
9386    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
9387    /// ````
9388    ///
9389    /// Sets the *delegate* property to the given value.
9390    pub fn delegate(
9391        mut self,
9392        new_value: &'a mut dyn common::Delegate,
9393    ) -> UserMessageGetCall<'a, C> {
9394        self._delegate = Some(new_value);
9395        self
9396    }
9397
9398    /// Set any additional parameter of the query string used in the request.
9399    /// It should be used to set parameters which are not yet available through their own
9400    /// setters.
9401    ///
9402    /// Please note that this method must not be used to set any of the known parameters
9403    /// which have their own setter method. If done anyway, the request will fail.
9404    ///
9405    /// # Additional Parameters
9406    ///
9407    /// * *$.xgafv* (query-string) - V1 error format.
9408    /// * *access_token* (query-string) - OAuth access token.
9409    /// * *alt* (query-string) - Data format for response.
9410    /// * *callback* (query-string) - JSONP
9411    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
9412    /// * *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.
9413    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
9414    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
9415    /// * *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.
9416    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
9417    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
9418    pub fn param<T>(mut self, name: T, value: T) -> UserMessageGetCall<'a, C>
9419    where
9420        T: AsRef<str>,
9421    {
9422        self._additional_params
9423            .insert(name.as_ref().to_string(), value.as_ref().to_string());
9424        self
9425    }
9426
9427    /// Identifies the authorization scope for the method you are building.
9428    ///
9429    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
9430    /// [`Scope::AddonCurrentMessageReadonly`].
9431    ///
9432    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
9433    /// tokens for more than one scope.
9434    ///
9435    /// Usually there is more than one suitable scope to authorize an operation, some of which may
9436    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
9437    /// sufficient, a read-write scope will do as well.
9438    pub fn add_scope<St>(mut self, scope: St) -> UserMessageGetCall<'a, C>
9439    where
9440        St: AsRef<str>,
9441    {
9442        self._scopes.insert(String::from(scope.as_ref()));
9443        self
9444    }
9445    /// Identifies the authorization scope(s) for the method you are building.
9446    ///
9447    /// See [`Self::add_scope()`] for details.
9448    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserMessageGetCall<'a, C>
9449    where
9450        I: IntoIterator<Item = St>,
9451        St: AsRef<str>,
9452    {
9453        self._scopes
9454            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
9455        self
9456    }
9457
9458    /// Removes all scopes, and no default scope will be used either.
9459    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
9460    /// for details).
9461    pub fn clear_scopes(mut self) -> UserMessageGetCall<'a, C> {
9462        self._scopes.clear();
9463        self
9464    }
9465}
9466
9467/// Imports a message into only this user's mailbox, with standard email delivery scanning and classification similar to receiving via SMTP. This method doesn't perform SPF checks, so it might not work for some spam messages, such as those attempting to perform domain spoofing. This method does not send a message.
9468///
9469/// A builder for the *messages.import* method supported by a *user* resource.
9470/// It is not used directly, but through a [`UserMethods`] instance.
9471///
9472/// # Example
9473///
9474/// Instantiate a resource method builder
9475///
9476/// ```test_harness,no_run
9477/// # extern crate hyper;
9478/// # extern crate hyper_rustls;
9479/// # extern crate google_gmail1 as gmail1;
9480/// use gmail1::api::Message;
9481/// use std::fs;
9482/// # async fn dox() {
9483/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
9484///
9485/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
9486/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
9487/// #     secret,
9488/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
9489/// # ).build().await.unwrap();
9490///
9491/// # let client = hyper_util::client::legacy::Client::builder(
9492/// #     hyper_util::rt::TokioExecutor::new()
9493/// # )
9494/// # .build(
9495/// #     hyper_rustls::HttpsConnectorBuilder::new()
9496/// #         .with_native_roots()
9497/// #         .unwrap()
9498/// #         .https_or_http()
9499/// #         .enable_http1()
9500/// #         .build()
9501/// # );
9502/// # let mut hub = Gmail::new(client, auth);
9503/// // As the method needs a request, you would usually fill it with the desired information
9504/// // into the respective structure. Some of the parts shown here might not be applicable !
9505/// // Values shown here are possibly random and not representative !
9506/// let mut req = Message::default();
9507///
9508/// // You can configure optional parameters by calling the respective setters at will, and
9509/// // execute the final call using `upload_resumable(...)`.
9510/// // Values shown here are possibly random and not representative !
9511/// let result = hub.users().messages_import(req, "userId")
9512///              .process_for_calendar(false)
9513///              .never_mark_spam(false)
9514///              .internal_date_source("Stet")
9515///              .deleted(false)
9516///              .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()).await;
9517/// # }
9518/// ```
9519pub struct UserMessageImportCall<'a, C>
9520where
9521    C: 'a,
9522{
9523    hub: &'a Gmail<C>,
9524    _request: Message,
9525    _user_id: String,
9526    _process_for_calendar: Option<bool>,
9527    _never_mark_spam: Option<bool>,
9528    _internal_date_source: Option<String>,
9529    _deleted: Option<bool>,
9530    _delegate: Option<&'a mut dyn common::Delegate>,
9531    _additional_params: HashMap<String, String>,
9532    _scopes: BTreeSet<String>,
9533}
9534
9535impl<'a, C> common::CallBuilder for UserMessageImportCall<'a, C> {}
9536
9537impl<'a, C> UserMessageImportCall<'a, C>
9538where
9539    C: common::Connector,
9540{
9541    /// Perform the operation you have build so far.
9542    async fn doit<RS>(
9543        mut self,
9544        mut reader: RS,
9545        reader_mime_type: mime::Mime,
9546        protocol: common::UploadProtocol,
9547    ) -> common::Result<(common::Response, Message)>
9548    where
9549        RS: common::ReadSeek,
9550    {
9551        use std::borrow::Cow;
9552        use std::io::{Read, Seek};
9553
9554        use common::{url::Params, ToParts};
9555        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
9556
9557        let mut dd = common::DefaultDelegate;
9558        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
9559        dlg.begin(common::MethodInfo {
9560            id: "gmail.users.messages.import",
9561            http_method: hyper::Method::POST,
9562        });
9563
9564        for &field in [
9565            "alt",
9566            "userId",
9567            "processForCalendar",
9568            "neverMarkSpam",
9569            "internalDateSource",
9570            "deleted",
9571        ]
9572        .iter()
9573        {
9574            if self._additional_params.contains_key(field) {
9575                dlg.finished(false);
9576                return Err(common::Error::FieldClash(field));
9577            }
9578        }
9579
9580        let mut params = Params::with_capacity(8 + self._additional_params.len());
9581        params.push("userId", self._user_id);
9582        if let Some(value) = self._process_for_calendar.as_ref() {
9583            params.push("processForCalendar", value.to_string());
9584        }
9585        if let Some(value) = self._never_mark_spam.as_ref() {
9586            params.push("neverMarkSpam", value.to_string());
9587        }
9588        if let Some(value) = self._internal_date_source.as_ref() {
9589            params.push("internalDateSource", value);
9590        }
9591        if let Some(value) = self._deleted.as_ref() {
9592            params.push("deleted", value.to_string());
9593        }
9594
9595        params.extend(self._additional_params.iter());
9596
9597        params.push("alt", "json");
9598        let (mut url, upload_type) = if protocol == common::UploadProtocol::Resumable {
9599            (
9600                self.hub._root_url.clone()
9601                    + "resumable/upload/gmail/v1/users/{userId}/messages/import",
9602                "resumable",
9603            )
9604        } else if protocol == common::UploadProtocol::Simple {
9605            (
9606                self.hub._root_url.clone() + "upload/gmail/v1/users/{userId}/messages/import",
9607                "multipart",
9608            )
9609        } else {
9610            unreachable!()
9611        };
9612        params.push("uploadType", upload_type);
9613        if self._scopes.is_empty() {
9614            self._scopes.insert(Scope::Gmai.as_ref().to_string());
9615        }
9616
9617        #[allow(clippy::single_element_loop)]
9618        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
9619            url = params.uri_replacement(url, param_name, find_this, false);
9620        }
9621        {
9622            let to_remove = ["userId"];
9623            params.remove_params(&to_remove);
9624        }
9625
9626        let url = params.parse_with_url(&url);
9627
9628        let mut json_mime_type = mime::APPLICATION_JSON;
9629        let mut request_value_reader = {
9630            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
9631            common::remove_json_null_values(&mut value);
9632            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
9633            serde_json::to_writer(&mut dst, &value).unwrap();
9634            dst
9635        };
9636        let request_size = request_value_reader
9637            .seek(std::io::SeekFrom::End(0))
9638            .unwrap();
9639        request_value_reader
9640            .seek(std::io::SeekFrom::Start(0))
9641            .unwrap();
9642
9643        let mut upload_url_from_server;
9644
9645        loop {
9646            let token = match self
9647                .hub
9648                .auth
9649                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
9650                .await
9651            {
9652                Ok(token) => token,
9653                Err(e) => match dlg.token(e) {
9654                    Ok(token) => token,
9655                    Err(e) => {
9656                        dlg.finished(false);
9657                        return Err(common::Error::MissingToken(e));
9658                    }
9659                },
9660            };
9661            request_value_reader
9662                .seek(std::io::SeekFrom::Start(0))
9663                .unwrap();
9664            let mut req_result = {
9665                let mut mp_reader: common::MultiPartReader = Default::default();
9666                let (mut body_reader, content_type) = match protocol {
9667                    common::UploadProtocol::Simple => {
9668                        mp_reader.reserve_exact(2);
9669                        let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
9670                        reader.seek(std::io::SeekFrom::Start(0)).unwrap();
9671                        if size > 52428800 {
9672                            return Err(common::Error::UploadSizeLimitExceeded(size, 52428800));
9673                        }
9674                        mp_reader
9675                            .add_part(
9676                                &mut request_value_reader,
9677                                request_size,
9678                                json_mime_type.clone(),
9679                            )
9680                            .add_part(&mut reader, size, reader_mime_type.clone());
9681                        (
9682                            &mut mp_reader as &mut (dyn std::io::Read + Send),
9683                            common::MultiPartReader::mime_type(),
9684                        )
9685                    }
9686                    _ => (
9687                        &mut request_value_reader as &mut (dyn std::io::Read + Send),
9688                        json_mime_type.clone(),
9689                    ),
9690                };
9691                let client = &self.hub.client;
9692                dlg.pre_request();
9693                let mut req_builder = hyper::Request::builder()
9694                    .method(hyper::Method::POST)
9695                    .uri(url.as_str())
9696                    .header(USER_AGENT, self.hub._user_agent.clone());
9697
9698                if let Some(token) = token.as_ref() {
9699                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
9700                }
9701
9702                upload_url_from_server = true;
9703                if protocol == common::UploadProtocol::Resumable {
9704                    req_builder = req_builder
9705                        .header("X-Upload-Content-Type", format!("{}", reader_mime_type));
9706                }
9707
9708                let mut body_reader_bytes = vec![];
9709                body_reader.read_to_end(&mut body_reader_bytes).unwrap();
9710                let request = req_builder
9711                    .header(CONTENT_TYPE, content_type.to_string())
9712                    .body(common::to_body(body_reader_bytes.into()));
9713
9714                client.request(request.unwrap()).await
9715            };
9716
9717            match req_result {
9718                Err(err) => {
9719                    if let common::Retry::After(d) = dlg.http_error(&err) {
9720                        sleep(d).await;
9721                        continue;
9722                    }
9723                    dlg.finished(false);
9724                    return Err(common::Error::HttpError(err));
9725                }
9726                Ok(res) => {
9727                    let (mut parts, body) = res.into_parts();
9728                    let mut body = common::Body::new(body);
9729                    if !parts.status.is_success() {
9730                        let bytes = common::to_bytes(body).await.unwrap_or_default();
9731                        let error = serde_json::from_str(&common::to_string(&bytes));
9732                        let response = common::to_response(parts, bytes.into());
9733
9734                        if let common::Retry::After(d) =
9735                            dlg.http_failure(&response, error.as_ref().ok())
9736                        {
9737                            sleep(d).await;
9738                            continue;
9739                        }
9740
9741                        dlg.finished(false);
9742
9743                        return Err(match error {
9744                            Ok(value) => common::Error::BadRequest(value),
9745                            _ => common::Error::Failure(response),
9746                        });
9747                    }
9748                    if protocol == common::UploadProtocol::Resumable {
9749                        let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
9750                        reader.seek(std::io::SeekFrom::Start(0)).unwrap();
9751                        if size > 52428800 {
9752                            return Err(common::Error::UploadSizeLimitExceeded(size, 52428800));
9753                        }
9754                        let upload_result = {
9755                            let url_str = &parts
9756                                .headers
9757                                .get("Location")
9758                                .expect("LOCATION header is part of protocol")
9759                                .to_str()
9760                                .unwrap();
9761                            if upload_url_from_server {
9762                                dlg.store_upload_url(Some(url_str));
9763                            }
9764
9765                            common::ResumableUploadHelper {
9766                                client: &self.hub.client,
9767                                delegate: dlg,
9768                                start_at: if upload_url_from_server {
9769                                    Some(0)
9770                                } else {
9771                                    None
9772                                },
9773                                auth: &self.hub.auth,
9774                                user_agent: &self.hub._user_agent,
9775                                // TODO: Check this assumption
9776                                auth_header: format!(
9777                                    "Bearer {}",
9778                                    token
9779                                        .ok_or_else(|| common::Error::MissingToken(
9780                                            "resumable upload requires token".into()
9781                                        ))?
9782                                        .as_str()
9783                                ),
9784                                url: url_str,
9785                                reader: &mut reader,
9786                                media_type: reader_mime_type.clone(),
9787                                content_length: size,
9788                            }
9789                            .upload()
9790                            .await
9791                        };
9792                        match upload_result {
9793                            None => {
9794                                dlg.finished(false);
9795                                return Err(common::Error::Cancelled);
9796                            }
9797                            Some(Err(err)) => {
9798                                dlg.finished(false);
9799                                return Err(common::Error::HttpError(err));
9800                            }
9801                            Some(Ok(response)) => {
9802                                (parts, body) = response.into_parts();
9803                                if !parts.status.is_success() {
9804                                    dlg.store_upload_url(None);
9805                                    dlg.finished(false);
9806                                    return Err(common::Error::Failure(
9807                                        common::Response::from_parts(parts, body),
9808                                    ));
9809                                }
9810                            }
9811                        }
9812                    }
9813                    let response = {
9814                        let bytes = common::to_bytes(body).await.unwrap_or_default();
9815                        let encoded = common::to_string(&bytes);
9816                        match serde_json::from_str(&encoded) {
9817                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
9818                            Err(error) => {
9819                                dlg.response_json_decode_error(&encoded, &error);
9820                                return Err(common::Error::JsonDecodeError(
9821                                    encoded.to_string(),
9822                                    error,
9823                                ));
9824                            }
9825                        }
9826                    };
9827
9828                    dlg.finished(true);
9829                    return Ok(response);
9830                }
9831            }
9832        }
9833    }
9834
9835    /// Upload media in a resumable fashion.
9836    /// Even if the upload fails or is interrupted, it can be resumed for a
9837    /// certain amount of time as the server maintains state temporarily.
9838    ///
9839    /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL
9840    /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate
9841    /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using
9842    /// `cancel_chunk_upload(...)`.
9843    ///
9844    /// * *multipart*: yes
9845    /// * *max size*: 52428800
9846    /// * *valid mime types*: 'message/*'
9847    pub async fn upload_resumable<RS>(
9848        self,
9849        resumeable_stream: RS,
9850        mime_type: mime::Mime,
9851    ) -> common::Result<(common::Response, Message)>
9852    where
9853        RS: common::ReadSeek,
9854    {
9855        self.doit(
9856            resumeable_stream,
9857            mime_type,
9858            common::UploadProtocol::Resumable,
9859        )
9860        .await
9861    }
9862    /// Upload media all at once.
9863    /// If the upload fails for whichever reason, all progress is lost.
9864    ///
9865    /// * *multipart*: yes
9866    /// * *max size*: 52428800
9867    /// * *valid mime types*: 'message/*'
9868    pub async fn upload<RS>(
9869        self,
9870        stream: RS,
9871        mime_type: mime::Mime,
9872    ) -> common::Result<(common::Response, Message)>
9873    where
9874        RS: common::ReadSeek,
9875    {
9876        self.doit(stream, mime_type, common::UploadProtocol::Simple)
9877            .await
9878    }
9879
9880    ///
9881    /// Sets the *request* property to the given value.
9882    ///
9883    /// Even though the property as already been set when instantiating this call,
9884    /// we provide this method for API completeness.
9885    pub fn request(mut self, new_value: Message) -> UserMessageImportCall<'a, C> {
9886        self._request = new_value;
9887        self
9888    }
9889    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
9890    ///
9891    /// Sets the *user id* path property to the given value.
9892    ///
9893    /// Even though the property as already been set when instantiating this call,
9894    /// we provide this method for API completeness.
9895    pub fn user_id(mut self, new_value: &str) -> UserMessageImportCall<'a, C> {
9896        self._user_id = new_value.to_string();
9897        self
9898    }
9899    /// Process calendar invites in the email and add any extracted meetings to the Google Calendar for this user.
9900    ///
9901    /// Sets the *process for calendar* query property to the given value.
9902    pub fn process_for_calendar(mut self, new_value: bool) -> UserMessageImportCall<'a, C> {
9903        self._process_for_calendar = Some(new_value);
9904        self
9905    }
9906    /// Ignore the Gmail spam classifier decision and never mark this email as SPAM in the mailbox.
9907    ///
9908    /// Sets the *never mark spam* query property to the given value.
9909    pub fn never_mark_spam(mut self, new_value: bool) -> UserMessageImportCall<'a, C> {
9910        self._never_mark_spam = Some(new_value);
9911        self
9912    }
9913    /// Source for Gmail's internal date of the message.
9914    ///
9915    /// Sets the *internal date source* query property to the given value.
9916    pub fn internal_date_source(mut self, new_value: &str) -> UserMessageImportCall<'a, C> {
9917        self._internal_date_source = Some(new_value.to_string());
9918        self
9919    }
9920    /// Mark the email as permanently deleted (not TRASH) and only visible in Google Vault to a Vault administrator. Only used for Google Workspace accounts.
9921    ///
9922    /// Sets the *deleted* query property to the given value.
9923    pub fn deleted(mut self, new_value: bool) -> UserMessageImportCall<'a, C> {
9924        self._deleted = Some(new_value);
9925        self
9926    }
9927    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
9928    /// while executing the actual API request.
9929    ///
9930    /// ````text
9931    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
9932    /// ````
9933    ///
9934    /// Sets the *delegate* property to the given value.
9935    pub fn delegate(
9936        mut self,
9937        new_value: &'a mut dyn common::Delegate,
9938    ) -> UserMessageImportCall<'a, C> {
9939        self._delegate = Some(new_value);
9940        self
9941    }
9942
9943    /// Set any additional parameter of the query string used in the request.
9944    /// It should be used to set parameters which are not yet available through their own
9945    /// setters.
9946    ///
9947    /// Please note that this method must not be used to set any of the known parameters
9948    /// which have their own setter method. If done anyway, the request will fail.
9949    ///
9950    /// # Additional Parameters
9951    ///
9952    /// * *$.xgafv* (query-string) - V1 error format.
9953    /// * *access_token* (query-string) - OAuth access token.
9954    /// * *alt* (query-string) - Data format for response.
9955    /// * *callback* (query-string) - JSONP
9956    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
9957    /// * *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.
9958    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
9959    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
9960    /// * *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.
9961    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
9962    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
9963    pub fn param<T>(mut self, name: T, value: T) -> UserMessageImportCall<'a, C>
9964    where
9965        T: AsRef<str>,
9966    {
9967        self._additional_params
9968            .insert(name.as_ref().to_string(), value.as_ref().to_string());
9969        self
9970    }
9971
9972    /// Identifies the authorization scope for the method you are building.
9973    ///
9974    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
9975    /// [`Scope::Gmai`].
9976    ///
9977    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
9978    /// tokens for more than one scope.
9979    ///
9980    /// Usually there is more than one suitable scope to authorize an operation, some of which may
9981    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
9982    /// sufficient, a read-write scope will do as well.
9983    pub fn add_scope<St>(mut self, scope: St) -> UserMessageImportCall<'a, C>
9984    where
9985        St: AsRef<str>,
9986    {
9987        self._scopes.insert(String::from(scope.as_ref()));
9988        self
9989    }
9990    /// Identifies the authorization scope(s) for the method you are building.
9991    ///
9992    /// See [`Self::add_scope()`] for details.
9993    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserMessageImportCall<'a, C>
9994    where
9995        I: IntoIterator<Item = St>,
9996        St: AsRef<str>,
9997    {
9998        self._scopes
9999            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
10000        self
10001    }
10002
10003    /// Removes all scopes, and no default scope will be used either.
10004    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
10005    /// for details).
10006    pub fn clear_scopes(mut self) -> UserMessageImportCall<'a, C> {
10007        self._scopes.clear();
10008        self
10009    }
10010}
10011
10012/// Directly inserts a message into only this user's mailbox similar to `IMAP APPEND`, bypassing most scanning and classification. Does not send a message.
10013///
10014/// A builder for the *messages.insert* method supported by a *user* resource.
10015/// It is not used directly, but through a [`UserMethods`] instance.
10016///
10017/// # Example
10018///
10019/// Instantiate a resource method builder
10020///
10021/// ```test_harness,no_run
10022/// # extern crate hyper;
10023/// # extern crate hyper_rustls;
10024/// # extern crate google_gmail1 as gmail1;
10025/// use gmail1::api::Message;
10026/// use std::fs;
10027/// # async fn dox() {
10028/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
10029///
10030/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
10031/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
10032/// #     secret,
10033/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
10034/// # ).build().await.unwrap();
10035///
10036/// # let client = hyper_util::client::legacy::Client::builder(
10037/// #     hyper_util::rt::TokioExecutor::new()
10038/// # )
10039/// # .build(
10040/// #     hyper_rustls::HttpsConnectorBuilder::new()
10041/// #         .with_native_roots()
10042/// #         .unwrap()
10043/// #         .https_or_http()
10044/// #         .enable_http1()
10045/// #         .build()
10046/// # );
10047/// # let mut hub = Gmail::new(client, auth);
10048/// // As the method needs a request, you would usually fill it with the desired information
10049/// // into the respective structure. Some of the parts shown here might not be applicable !
10050/// // Values shown here are possibly random and not representative !
10051/// let mut req = Message::default();
10052///
10053/// // You can configure optional parameters by calling the respective setters at will, and
10054/// // execute the final call using `upload_resumable(...)`.
10055/// // Values shown here are possibly random and not representative !
10056/// let result = hub.users().messages_insert(req, "userId")
10057///              .internal_date_source("Lorem")
10058///              .deleted(true)
10059///              .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()).await;
10060/// # }
10061/// ```
10062pub struct UserMessageInsertCall<'a, C>
10063where
10064    C: 'a,
10065{
10066    hub: &'a Gmail<C>,
10067    _request: Message,
10068    _user_id: String,
10069    _internal_date_source: Option<String>,
10070    _deleted: Option<bool>,
10071    _delegate: Option<&'a mut dyn common::Delegate>,
10072    _additional_params: HashMap<String, String>,
10073    _scopes: BTreeSet<String>,
10074}
10075
10076impl<'a, C> common::CallBuilder for UserMessageInsertCall<'a, C> {}
10077
10078impl<'a, C> UserMessageInsertCall<'a, C>
10079where
10080    C: common::Connector,
10081{
10082    /// Perform the operation you have build so far.
10083    async fn doit<RS>(
10084        mut self,
10085        mut reader: RS,
10086        reader_mime_type: mime::Mime,
10087        protocol: common::UploadProtocol,
10088    ) -> common::Result<(common::Response, Message)>
10089    where
10090        RS: common::ReadSeek,
10091    {
10092        use std::borrow::Cow;
10093        use std::io::{Read, Seek};
10094
10095        use common::{url::Params, ToParts};
10096        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
10097
10098        let mut dd = common::DefaultDelegate;
10099        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
10100        dlg.begin(common::MethodInfo {
10101            id: "gmail.users.messages.insert",
10102            http_method: hyper::Method::POST,
10103        });
10104
10105        for &field in ["alt", "userId", "internalDateSource", "deleted"].iter() {
10106            if self._additional_params.contains_key(field) {
10107                dlg.finished(false);
10108                return Err(common::Error::FieldClash(field));
10109            }
10110        }
10111
10112        let mut params = Params::with_capacity(6 + self._additional_params.len());
10113        params.push("userId", self._user_id);
10114        if let Some(value) = self._internal_date_source.as_ref() {
10115            params.push("internalDateSource", value);
10116        }
10117        if let Some(value) = self._deleted.as_ref() {
10118            params.push("deleted", value.to_string());
10119        }
10120
10121        params.extend(self._additional_params.iter());
10122
10123        params.push("alt", "json");
10124        let (mut url, upload_type) = if protocol == common::UploadProtocol::Resumable {
10125            (
10126                self.hub._root_url.clone() + "resumable/upload/gmail/v1/users/{userId}/messages",
10127                "resumable",
10128            )
10129        } else if protocol == common::UploadProtocol::Simple {
10130            (
10131                self.hub._root_url.clone() + "upload/gmail/v1/users/{userId}/messages",
10132                "multipart",
10133            )
10134        } else {
10135            unreachable!()
10136        };
10137        params.push("uploadType", upload_type);
10138        if self._scopes.is_empty() {
10139            self._scopes.insert(Scope::Gmai.as_ref().to_string());
10140        }
10141
10142        #[allow(clippy::single_element_loop)]
10143        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
10144            url = params.uri_replacement(url, param_name, find_this, false);
10145        }
10146        {
10147            let to_remove = ["userId"];
10148            params.remove_params(&to_remove);
10149        }
10150
10151        let url = params.parse_with_url(&url);
10152
10153        let mut json_mime_type = mime::APPLICATION_JSON;
10154        let mut request_value_reader = {
10155            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
10156            common::remove_json_null_values(&mut value);
10157            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
10158            serde_json::to_writer(&mut dst, &value).unwrap();
10159            dst
10160        };
10161        let request_size = request_value_reader
10162            .seek(std::io::SeekFrom::End(0))
10163            .unwrap();
10164        request_value_reader
10165            .seek(std::io::SeekFrom::Start(0))
10166            .unwrap();
10167
10168        let mut upload_url_from_server;
10169
10170        loop {
10171            let token = match self
10172                .hub
10173                .auth
10174                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
10175                .await
10176            {
10177                Ok(token) => token,
10178                Err(e) => match dlg.token(e) {
10179                    Ok(token) => token,
10180                    Err(e) => {
10181                        dlg.finished(false);
10182                        return Err(common::Error::MissingToken(e));
10183                    }
10184                },
10185            };
10186            request_value_reader
10187                .seek(std::io::SeekFrom::Start(0))
10188                .unwrap();
10189            let mut req_result = {
10190                let mut mp_reader: common::MultiPartReader = Default::default();
10191                let (mut body_reader, content_type) = match protocol {
10192                    common::UploadProtocol::Simple => {
10193                        mp_reader.reserve_exact(2);
10194                        let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
10195                        reader.seek(std::io::SeekFrom::Start(0)).unwrap();
10196                        if size > 52428800 {
10197                            return Err(common::Error::UploadSizeLimitExceeded(size, 52428800));
10198                        }
10199                        mp_reader
10200                            .add_part(
10201                                &mut request_value_reader,
10202                                request_size,
10203                                json_mime_type.clone(),
10204                            )
10205                            .add_part(&mut reader, size, reader_mime_type.clone());
10206                        (
10207                            &mut mp_reader as &mut (dyn std::io::Read + Send),
10208                            common::MultiPartReader::mime_type(),
10209                        )
10210                    }
10211                    _ => (
10212                        &mut request_value_reader as &mut (dyn std::io::Read + Send),
10213                        json_mime_type.clone(),
10214                    ),
10215                };
10216                let client = &self.hub.client;
10217                dlg.pre_request();
10218                let mut req_builder = hyper::Request::builder()
10219                    .method(hyper::Method::POST)
10220                    .uri(url.as_str())
10221                    .header(USER_AGENT, self.hub._user_agent.clone());
10222
10223                if let Some(token) = token.as_ref() {
10224                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
10225                }
10226
10227                upload_url_from_server = true;
10228                if protocol == common::UploadProtocol::Resumable {
10229                    req_builder = req_builder
10230                        .header("X-Upload-Content-Type", format!("{}", reader_mime_type));
10231                }
10232
10233                let mut body_reader_bytes = vec![];
10234                body_reader.read_to_end(&mut body_reader_bytes).unwrap();
10235                let request = req_builder
10236                    .header(CONTENT_TYPE, content_type.to_string())
10237                    .body(common::to_body(body_reader_bytes.into()));
10238
10239                client.request(request.unwrap()).await
10240            };
10241
10242            match req_result {
10243                Err(err) => {
10244                    if let common::Retry::After(d) = dlg.http_error(&err) {
10245                        sleep(d).await;
10246                        continue;
10247                    }
10248                    dlg.finished(false);
10249                    return Err(common::Error::HttpError(err));
10250                }
10251                Ok(res) => {
10252                    let (mut parts, body) = res.into_parts();
10253                    let mut body = common::Body::new(body);
10254                    if !parts.status.is_success() {
10255                        let bytes = common::to_bytes(body).await.unwrap_or_default();
10256                        let error = serde_json::from_str(&common::to_string(&bytes));
10257                        let response = common::to_response(parts, bytes.into());
10258
10259                        if let common::Retry::After(d) =
10260                            dlg.http_failure(&response, error.as_ref().ok())
10261                        {
10262                            sleep(d).await;
10263                            continue;
10264                        }
10265
10266                        dlg.finished(false);
10267
10268                        return Err(match error {
10269                            Ok(value) => common::Error::BadRequest(value),
10270                            _ => common::Error::Failure(response),
10271                        });
10272                    }
10273                    if protocol == common::UploadProtocol::Resumable {
10274                        let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
10275                        reader.seek(std::io::SeekFrom::Start(0)).unwrap();
10276                        if size > 52428800 {
10277                            return Err(common::Error::UploadSizeLimitExceeded(size, 52428800));
10278                        }
10279                        let upload_result = {
10280                            let url_str = &parts
10281                                .headers
10282                                .get("Location")
10283                                .expect("LOCATION header is part of protocol")
10284                                .to_str()
10285                                .unwrap();
10286                            if upload_url_from_server {
10287                                dlg.store_upload_url(Some(url_str));
10288                            }
10289
10290                            common::ResumableUploadHelper {
10291                                client: &self.hub.client,
10292                                delegate: dlg,
10293                                start_at: if upload_url_from_server {
10294                                    Some(0)
10295                                } else {
10296                                    None
10297                                },
10298                                auth: &self.hub.auth,
10299                                user_agent: &self.hub._user_agent,
10300                                // TODO: Check this assumption
10301                                auth_header: format!(
10302                                    "Bearer {}",
10303                                    token
10304                                        .ok_or_else(|| common::Error::MissingToken(
10305                                            "resumable upload requires token".into()
10306                                        ))?
10307                                        .as_str()
10308                                ),
10309                                url: url_str,
10310                                reader: &mut reader,
10311                                media_type: reader_mime_type.clone(),
10312                                content_length: size,
10313                            }
10314                            .upload()
10315                            .await
10316                        };
10317                        match upload_result {
10318                            None => {
10319                                dlg.finished(false);
10320                                return Err(common::Error::Cancelled);
10321                            }
10322                            Some(Err(err)) => {
10323                                dlg.finished(false);
10324                                return Err(common::Error::HttpError(err));
10325                            }
10326                            Some(Ok(response)) => {
10327                                (parts, body) = response.into_parts();
10328                                if !parts.status.is_success() {
10329                                    dlg.store_upload_url(None);
10330                                    dlg.finished(false);
10331                                    return Err(common::Error::Failure(
10332                                        common::Response::from_parts(parts, body),
10333                                    ));
10334                                }
10335                            }
10336                        }
10337                    }
10338                    let response = {
10339                        let bytes = common::to_bytes(body).await.unwrap_or_default();
10340                        let encoded = common::to_string(&bytes);
10341                        match serde_json::from_str(&encoded) {
10342                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
10343                            Err(error) => {
10344                                dlg.response_json_decode_error(&encoded, &error);
10345                                return Err(common::Error::JsonDecodeError(
10346                                    encoded.to_string(),
10347                                    error,
10348                                ));
10349                            }
10350                        }
10351                    };
10352
10353                    dlg.finished(true);
10354                    return Ok(response);
10355                }
10356            }
10357        }
10358    }
10359
10360    /// Upload media in a resumable fashion.
10361    /// Even if the upload fails or is interrupted, it can be resumed for a
10362    /// certain amount of time as the server maintains state temporarily.
10363    ///
10364    /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL
10365    /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate
10366    /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using
10367    /// `cancel_chunk_upload(...)`.
10368    ///
10369    /// * *multipart*: yes
10370    /// * *max size*: 52428800
10371    /// * *valid mime types*: 'message/*'
10372    pub async fn upload_resumable<RS>(
10373        self,
10374        resumeable_stream: RS,
10375        mime_type: mime::Mime,
10376    ) -> common::Result<(common::Response, Message)>
10377    where
10378        RS: common::ReadSeek,
10379    {
10380        self.doit(
10381            resumeable_stream,
10382            mime_type,
10383            common::UploadProtocol::Resumable,
10384        )
10385        .await
10386    }
10387    /// Upload media all at once.
10388    /// If the upload fails for whichever reason, all progress is lost.
10389    ///
10390    /// * *multipart*: yes
10391    /// * *max size*: 52428800
10392    /// * *valid mime types*: 'message/*'
10393    pub async fn upload<RS>(
10394        self,
10395        stream: RS,
10396        mime_type: mime::Mime,
10397    ) -> common::Result<(common::Response, Message)>
10398    where
10399        RS: common::ReadSeek,
10400    {
10401        self.doit(stream, mime_type, common::UploadProtocol::Simple)
10402            .await
10403    }
10404
10405    ///
10406    /// Sets the *request* property to the given value.
10407    ///
10408    /// Even though the property as already been set when instantiating this call,
10409    /// we provide this method for API completeness.
10410    pub fn request(mut self, new_value: Message) -> UserMessageInsertCall<'a, C> {
10411        self._request = new_value;
10412        self
10413    }
10414    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
10415    ///
10416    /// Sets the *user id* path property to the given value.
10417    ///
10418    /// Even though the property as already been set when instantiating this call,
10419    /// we provide this method for API completeness.
10420    pub fn user_id(mut self, new_value: &str) -> UserMessageInsertCall<'a, C> {
10421        self._user_id = new_value.to_string();
10422        self
10423    }
10424    /// Source for Gmail's internal date of the message.
10425    ///
10426    /// Sets the *internal date source* query property to the given value.
10427    pub fn internal_date_source(mut self, new_value: &str) -> UserMessageInsertCall<'a, C> {
10428        self._internal_date_source = Some(new_value.to_string());
10429        self
10430    }
10431    /// Mark the email as permanently deleted (not TRASH) and only visible in Google Vault to a Vault administrator. Only used for Google Workspace accounts.
10432    ///
10433    /// Sets the *deleted* query property to the given value.
10434    pub fn deleted(mut self, new_value: bool) -> UserMessageInsertCall<'a, C> {
10435        self._deleted = Some(new_value);
10436        self
10437    }
10438    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
10439    /// while executing the actual API request.
10440    ///
10441    /// ````text
10442    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
10443    /// ````
10444    ///
10445    /// Sets the *delegate* property to the given value.
10446    pub fn delegate(
10447        mut self,
10448        new_value: &'a mut dyn common::Delegate,
10449    ) -> UserMessageInsertCall<'a, C> {
10450        self._delegate = Some(new_value);
10451        self
10452    }
10453
10454    /// Set any additional parameter of the query string used in the request.
10455    /// It should be used to set parameters which are not yet available through their own
10456    /// setters.
10457    ///
10458    /// Please note that this method must not be used to set any of the known parameters
10459    /// which have their own setter method. If done anyway, the request will fail.
10460    ///
10461    /// # Additional Parameters
10462    ///
10463    /// * *$.xgafv* (query-string) - V1 error format.
10464    /// * *access_token* (query-string) - OAuth access token.
10465    /// * *alt* (query-string) - Data format for response.
10466    /// * *callback* (query-string) - JSONP
10467    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
10468    /// * *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.
10469    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
10470    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
10471    /// * *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.
10472    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
10473    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
10474    pub fn param<T>(mut self, name: T, value: T) -> UserMessageInsertCall<'a, C>
10475    where
10476        T: AsRef<str>,
10477    {
10478        self._additional_params
10479            .insert(name.as_ref().to_string(), value.as_ref().to_string());
10480        self
10481    }
10482
10483    /// Identifies the authorization scope for the method you are building.
10484    ///
10485    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
10486    /// [`Scope::Gmai`].
10487    ///
10488    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
10489    /// tokens for more than one scope.
10490    ///
10491    /// Usually there is more than one suitable scope to authorize an operation, some of which may
10492    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
10493    /// sufficient, a read-write scope will do as well.
10494    pub fn add_scope<St>(mut self, scope: St) -> UserMessageInsertCall<'a, C>
10495    where
10496        St: AsRef<str>,
10497    {
10498        self._scopes.insert(String::from(scope.as_ref()));
10499        self
10500    }
10501    /// Identifies the authorization scope(s) for the method you are building.
10502    ///
10503    /// See [`Self::add_scope()`] for details.
10504    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserMessageInsertCall<'a, C>
10505    where
10506        I: IntoIterator<Item = St>,
10507        St: AsRef<str>,
10508    {
10509        self._scopes
10510            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
10511        self
10512    }
10513
10514    /// Removes all scopes, and no default scope will be used either.
10515    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
10516    /// for details).
10517    pub fn clear_scopes(mut self) -> UserMessageInsertCall<'a, C> {
10518        self._scopes.clear();
10519        self
10520    }
10521}
10522
10523/// Lists the messages in the user's mailbox.
10524///
10525/// A builder for the *messages.list* method supported by a *user* resource.
10526/// It is not used directly, but through a [`UserMethods`] instance.
10527///
10528/// # Example
10529///
10530/// Instantiate a resource method builder
10531///
10532/// ```test_harness,no_run
10533/// # extern crate hyper;
10534/// # extern crate hyper_rustls;
10535/// # extern crate google_gmail1 as gmail1;
10536/// # async fn dox() {
10537/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
10538///
10539/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
10540/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
10541/// #     secret,
10542/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
10543/// # ).build().await.unwrap();
10544///
10545/// # let client = hyper_util::client::legacy::Client::builder(
10546/// #     hyper_util::rt::TokioExecutor::new()
10547/// # )
10548/// # .build(
10549/// #     hyper_rustls::HttpsConnectorBuilder::new()
10550/// #         .with_native_roots()
10551/// #         .unwrap()
10552/// #         .https_or_http()
10553/// #         .enable_http1()
10554/// #         .build()
10555/// # );
10556/// # let mut hub = Gmail::new(client, auth);
10557/// // You can configure optional parameters by calling the respective setters at will, and
10558/// // execute the final call using `doit()`.
10559/// // Values shown here are possibly random and not representative !
10560/// let result = hub.users().messages_list("userId")
10561///              .q("accusam")
10562///              .page_token("takimata")
10563///              .max_results(55)
10564///              .add_label_ids("voluptua.")
10565///              .include_spam_trash(false)
10566///              .doit().await;
10567/// # }
10568/// ```
10569pub struct UserMessageListCall<'a, C>
10570where
10571    C: 'a,
10572{
10573    hub: &'a Gmail<C>,
10574    _user_id: String,
10575    _q: Option<String>,
10576    _page_token: Option<String>,
10577    _max_results: Option<u32>,
10578    _label_ids: Vec<String>,
10579    _include_spam_trash: Option<bool>,
10580    _delegate: Option<&'a mut dyn common::Delegate>,
10581    _additional_params: HashMap<String, String>,
10582    _scopes: BTreeSet<String>,
10583}
10584
10585impl<'a, C> common::CallBuilder for UserMessageListCall<'a, C> {}
10586
10587impl<'a, C> UserMessageListCall<'a, C>
10588where
10589    C: common::Connector,
10590{
10591    /// Perform the operation you have build so far.
10592    pub async fn doit(mut self) -> common::Result<(common::Response, ListMessagesResponse)> {
10593        use std::borrow::Cow;
10594        use std::io::{Read, Seek};
10595
10596        use common::{url::Params, ToParts};
10597        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
10598
10599        let mut dd = common::DefaultDelegate;
10600        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
10601        dlg.begin(common::MethodInfo {
10602            id: "gmail.users.messages.list",
10603            http_method: hyper::Method::GET,
10604        });
10605
10606        for &field in [
10607            "alt",
10608            "userId",
10609            "q",
10610            "pageToken",
10611            "maxResults",
10612            "labelIds",
10613            "includeSpamTrash",
10614        ]
10615        .iter()
10616        {
10617            if self._additional_params.contains_key(field) {
10618                dlg.finished(false);
10619                return Err(common::Error::FieldClash(field));
10620            }
10621        }
10622
10623        let mut params = Params::with_capacity(8 + self._additional_params.len());
10624        params.push("userId", self._user_id);
10625        if let Some(value) = self._q.as_ref() {
10626            params.push("q", value);
10627        }
10628        if let Some(value) = self._page_token.as_ref() {
10629            params.push("pageToken", value);
10630        }
10631        if let Some(value) = self._max_results.as_ref() {
10632            params.push("maxResults", value.to_string());
10633        }
10634        if !self._label_ids.is_empty() {
10635            for f in self._label_ids.iter() {
10636                params.push("labelIds", f);
10637            }
10638        }
10639        if let Some(value) = self._include_spam_trash.as_ref() {
10640            params.push("includeSpamTrash", value.to_string());
10641        }
10642
10643        params.extend(self._additional_params.iter());
10644
10645        params.push("alt", "json");
10646        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/messages";
10647        if self._scopes.is_empty() {
10648            self._scopes.insert(Scope::Readonly.as_ref().to_string());
10649        }
10650
10651        #[allow(clippy::single_element_loop)]
10652        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
10653            url = params.uri_replacement(url, param_name, find_this, false);
10654        }
10655        {
10656            let to_remove = ["userId"];
10657            params.remove_params(&to_remove);
10658        }
10659
10660        let url = params.parse_with_url(&url);
10661
10662        loop {
10663            let token = match self
10664                .hub
10665                .auth
10666                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
10667                .await
10668            {
10669                Ok(token) => token,
10670                Err(e) => match dlg.token(e) {
10671                    Ok(token) => token,
10672                    Err(e) => {
10673                        dlg.finished(false);
10674                        return Err(common::Error::MissingToken(e));
10675                    }
10676                },
10677            };
10678            let mut req_result = {
10679                let client = &self.hub.client;
10680                dlg.pre_request();
10681                let mut req_builder = hyper::Request::builder()
10682                    .method(hyper::Method::GET)
10683                    .uri(url.as_str())
10684                    .header(USER_AGENT, self.hub._user_agent.clone());
10685
10686                if let Some(token) = token.as_ref() {
10687                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
10688                }
10689
10690                let request = req_builder
10691                    .header(CONTENT_LENGTH, 0_u64)
10692                    .body(common::to_body::<String>(None));
10693
10694                client.request(request.unwrap()).await
10695            };
10696
10697            match req_result {
10698                Err(err) => {
10699                    if let common::Retry::After(d) = dlg.http_error(&err) {
10700                        sleep(d).await;
10701                        continue;
10702                    }
10703                    dlg.finished(false);
10704                    return Err(common::Error::HttpError(err));
10705                }
10706                Ok(res) => {
10707                    let (mut parts, body) = res.into_parts();
10708                    let mut body = common::Body::new(body);
10709                    if !parts.status.is_success() {
10710                        let bytes = common::to_bytes(body).await.unwrap_or_default();
10711                        let error = serde_json::from_str(&common::to_string(&bytes));
10712                        let response = common::to_response(parts, bytes.into());
10713
10714                        if let common::Retry::After(d) =
10715                            dlg.http_failure(&response, error.as_ref().ok())
10716                        {
10717                            sleep(d).await;
10718                            continue;
10719                        }
10720
10721                        dlg.finished(false);
10722
10723                        return Err(match error {
10724                            Ok(value) => common::Error::BadRequest(value),
10725                            _ => common::Error::Failure(response),
10726                        });
10727                    }
10728                    let response = {
10729                        let bytes = common::to_bytes(body).await.unwrap_or_default();
10730                        let encoded = common::to_string(&bytes);
10731                        match serde_json::from_str(&encoded) {
10732                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
10733                            Err(error) => {
10734                                dlg.response_json_decode_error(&encoded, &error);
10735                                return Err(common::Error::JsonDecodeError(
10736                                    encoded.to_string(),
10737                                    error,
10738                                ));
10739                            }
10740                        }
10741                    };
10742
10743                    dlg.finished(true);
10744                    return Ok(response);
10745                }
10746            }
10747        }
10748    }
10749
10750    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
10751    ///
10752    /// Sets the *user id* path property to the given value.
10753    ///
10754    /// Even though the property as already been set when instantiating this call,
10755    /// we provide this method for API completeness.
10756    pub fn user_id(mut self, new_value: &str) -> UserMessageListCall<'a, C> {
10757        self._user_id = new_value.to_string();
10758        self
10759    }
10760    /// Only return messages matching the specified query. Supports the same query format as the Gmail search box. For example, `"from:someuser@example.com rfc822msgid: is:unread"`. Parameter cannot be used when accessing the api using the gmail.metadata scope.
10761    ///
10762    /// Sets the *q* query property to the given value.
10763    pub fn q(mut self, new_value: &str) -> UserMessageListCall<'a, C> {
10764        self._q = Some(new_value.to_string());
10765        self
10766    }
10767    /// Page token to retrieve a specific page of results in the list.
10768    ///
10769    /// Sets the *page token* query property to the given value.
10770    pub fn page_token(mut self, new_value: &str) -> UserMessageListCall<'a, C> {
10771        self._page_token = Some(new_value.to_string());
10772        self
10773    }
10774    /// Maximum number of messages to return. This field defaults to 100. The maximum allowed value for this field is 500.
10775    ///
10776    /// Sets the *max results* query property to the given value.
10777    pub fn max_results(mut self, new_value: u32) -> UserMessageListCall<'a, C> {
10778        self._max_results = Some(new_value);
10779        self
10780    }
10781    /// Only return messages with labels that match all of the specified label IDs. Messages in a thread might have labels that other messages in the same thread don't have. To learn more, see [Manage labels on messages and threads](https://developers.google.com/gmail/api/guides/labels#manage_labels_on_messages_threads).
10782    ///
10783    /// Append the given value to the *label ids* query property.
10784    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
10785    pub fn add_label_ids(mut self, new_value: &str) -> UserMessageListCall<'a, C> {
10786        self._label_ids.push(new_value.to_string());
10787        self
10788    }
10789    /// Include messages from `SPAM` and `TRASH` in the results.
10790    ///
10791    /// Sets the *include spam trash* query property to the given value.
10792    pub fn include_spam_trash(mut self, new_value: bool) -> UserMessageListCall<'a, C> {
10793        self._include_spam_trash = Some(new_value);
10794        self
10795    }
10796    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
10797    /// while executing the actual API request.
10798    ///
10799    /// ````text
10800    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
10801    /// ````
10802    ///
10803    /// Sets the *delegate* property to the given value.
10804    pub fn delegate(
10805        mut self,
10806        new_value: &'a mut dyn common::Delegate,
10807    ) -> UserMessageListCall<'a, C> {
10808        self._delegate = Some(new_value);
10809        self
10810    }
10811
10812    /// Set any additional parameter of the query string used in the request.
10813    /// It should be used to set parameters which are not yet available through their own
10814    /// setters.
10815    ///
10816    /// Please note that this method must not be used to set any of the known parameters
10817    /// which have their own setter method. If done anyway, the request will fail.
10818    ///
10819    /// # Additional Parameters
10820    ///
10821    /// * *$.xgafv* (query-string) - V1 error format.
10822    /// * *access_token* (query-string) - OAuth access token.
10823    /// * *alt* (query-string) - Data format for response.
10824    /// * *callback* (query-string) - JSONP
10825    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
10826    /// * *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.
10827    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
10828    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
10829    /// * *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.
10830    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
10831    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
10832    pub fn param<T>(mut self, name: T, value: T) -> UserMessageListCall<'a, C>
10833    where
10834        T: AsRef<str>,
10835    {
10836        self._additional_params
10837            .insert(name.as_ref().to_string(), value.as_ref().to_string());
10838        self
10839    }
10840
10841    /// Identifies the authorization scope for the method you are building.
10842    ///
10843    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
10844    /// [`Scope::Readonly`].
10845    ///
10846    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
10847    /// tokens for more than one scope.
10848    ///
10849    /// Usually there is more than one suitable scope to authorize an operation, some of which may
10850    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
10851    /// sufficient, a read-write scope will do as well.
10852    pub fn add_scope<St>(mut self, scope: St) -> UserMessageListCall<'a, C>
10853    where
10854        St: AsRef<str>,
10855    {
10856        self._scopes.insert(String::from(scope.as_ref()));
10857        self
10858    }
10859    /// Identifies the authorization scope(s) for the method you are building.
10860    ///
10861    /// See [`Self::add_scope()`] for details.
10862    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserMessageListCall<'a, C>
10863    where
10864        I: IntoIterator<Item = St>,
10865        St: AsRef<str>,
10866    {
10867        self._scopes
10868            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
10869        self
10870    }
10871
10872    /// Removes all scopes, and no default scope will be used either.
10873    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
10874    /// for details).
10875    pub fn clear_scopes(mut self) -> UserMessageListCall<'a, C> {
10876        self._scopes.clear();
10877        self
10878    }
10879}
10880
10881/// Modifies the labels on the specified message.
10882///
10883/// A builder for the *messages.modify* method supported by a *user* resource.
10884/// It is not used directly, but through a [`UserMethods`] instance.
10885///
10886/// # Example
10887///
10888/// Instantiate a resource method builder
10889///
10890/// ```test_harness,no_run
10891/// # extern crate hyper;
10892/// # extern crate hyper_rustls;
10893/// # extern crate google_gmail1 as gmail1;
10894/// use gmail1::api::ModifyMessageRequest;
10895/// # async fn dox() {
10896/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
10897///
10898/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
10899/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
10900/// #     secret,
10901/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
10902/// # ).build().await.unwrap();
10903///
10904/// # let client = hyper_util::client::legacy::Client::builder(
10905/// #     hyper_util::rt::TokioExecutor::new()
10906/// # )
10907/// # .build(
10908/// #     hyper_rustls::HttpsConnectorBuilder::new()
10909/// #         .with_native_roots()
10910/// #         .unwrap()
10911/// #         .https_or_http()
10912/// #         .enable_http1()
10913/// #         .build()
10914/// # );
10915/// # let mut hub = Gmail::new(client, auth);
10916/// // As the method needs a request, you would usually fill it with the desired information
10917/// // into the respective structure. Some of the parts shown here might not be applicable !
10918/// // Values shown here are possibly random and not representative !
10919/// let mut req = ModifyMessageRequest::default();
10920///
10921/// // You can configure optional parameters by calling the respective setters at will, and
10922/// // execute the final call using `doit()`.
10923/// // Values shown here are possibly random and not representative !
10924/// let result = hub.users().messages_modify(req, "userId", "id")
10925///              .doit().await;
10926/// # }
10927/// ```
10928pub struct UserMessageModifyCall<'a, C>
10929where
10930    C: 'a,
10931{
10932    hub: &'a Gmail<C>,
10933    _request: ModifyMessageRequest,
10934    _user_id: String,
10935    _id: String,
10936    _delegate: Option<&'a mut dyn common::Delegate>,
10937    _additional_params: HashMap<String, String>,
10938    _scopes: BTreeSet<String>,
10939}
10940
10941impl<'a, C> common::CallBuilder for UserMessageModifyCall<'a, C> {}
10942
10943impl<'a, C> UserMessageModifyCall<'a, C>
10944where
10945    C: common::Connector,
10946{
10947    /// Perform the operation you have build so far.
10948    pub async fn doit(mut self) -> common::Result<(common::Response, Message)> {
10949        use std::borrow::Cow;
10950        use std::io::{Read, Seek};
10951
10952        use common::{url::Params, ToParts};
10953        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
10954
10955        let mut dd = common::DefaultDelegate;
10956        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
10957        dlg.begin(common::MethodInfo {
10958            id: "gmail.users.messages.modify",
10959            http_method: hyper::Method::POST,
10960        });
10961
10962        for &field in ["alt", "userId", "id"].iter() {
10963            if self._additional_params.contains_key(field) {
10964                dlg.finished(false);
10965                return Err(common::Error::FieldClash(field));
10966            }
10967        }
10968
10969        let mut params = Params::with_capacity(5 + self._additional_params.len());
10970        params.push("userId", self._user_id);
10971        params.push("id", self._id);
10972
10973        params.extend(self._additional_params.iter());
10974
10975        params.push("alt", "json");
10976        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/messages/{id}/modify";
10977        if self._scopes.is_empty() {
10978            self._scopes.insert(Scope::Gmai.as_ref().to_string());
10979        }
10980
10981        #[allow(clippy::single_element_loop)]
10982        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
10983            url = params.uri_replacement(url, param_name, find_this, false);
10984        }
10985        {
10986            let to_remove = ["id", "userId"];
10987            params.remove_params(&to_remove);
10988        }
10989
10990        let url = params.parse_with_url(&url);
10991
10992        let mut json_mime_type = mime::APPLICATION_JSON;
10993        let mut request_value_reader = {
10994            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
10995            common::remove_json_null_values(&mut value);
10996            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
10997            serde_json::to_writer(&mut dst, &value).unwrap();
10998            dst
10999        };
11000        let request_size = request_value_reader
11001            .seek(std::io::SeekFrom::End(0))
11002            .unwrap();
11003        request_value_reader
11004            .seek(std::io::SeekFrom::Start(0))
11005            .unwrap();
11006
11007        loop {
11008            let token = match self
11009                .hub
11010                .auth
11011                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
11012                .await
11013            {
11014                Ok(token) => token,
11015                Err(e) => match dlg.token(e) {
11016                    Ok(token) => token,
11017                    Err(e) => {
11018                        dlg.finished(false);
11019                        return Err(common::Error::MissingToken(e));
11020                    }
11021                },
11022            };
11023            request_value_reader
11024                .seek(std::io::SeekFrom::Start(0))
11025                .unwrap();
11026            let mut req_result = {
11027                let client = &self.hub.client;
11028                dlg.pre_request();
11029                let mut req_builder = hyper::Request::builder()
11030                    .method(hyper::Method::POST)
11031                    .uri(url.as_str())
11032                    .header(USER_AGENT, self.hub._user_agent.clone());
11033
11034                if let Some(token) = token.as_ref() {
11035                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
11036                }
11037
11038                let request = req_builder
11039                    .header(CONTENT_TYPE, json_mime_type.to_string())
11040                    .header(CONTENT_LENGTH, request_size as u64)
11041                    .body(common::to_body(
11042                        request_value_reader.get_ref().clone().into(),
11043                    ));
11044
11045                client.request(request.unwrap()).await
11046            };
11047
11048            match req_result {
11049                Err(err) => {
11050                    if let common::Retry::After(d) = dlg.http_error(&err) {
11051                        sleep(d).await;
11052                        continue;
11053                    }
11054                    dlg.finished(false);
11055                    return Err(common::Error::HttpError(err));
11056                }
11057                Ok(res) => {
11058                    let (mut parts, body) = res.into_parts();
11059                    let mut body = common::Body::new(body);
11060                    if !parts.status.is_success() {
11061                        let bytes = common::to_bytes(body).await.unwrap_or_default();
11062                        let error = serde_json::from_str(&common::to_string(&bytes));
11063                        let response = common::to_response(parts, bytes.into());
11064
11065                        if let common::Retry::After(d) =
11066                            dlg.http_failure(&response, error.as_ref().ok())
11067                        {
11068                            sleep(d).await;
11069                            continue;
11070                        }
11071
11072                        dlg.finished(false);
11073
11074                        return Err(match error {
11075                            Ok(value) => common::Error::BadRequest(value),
11076                            _ => common::Error::Failure(response),
11077                        });
11078                    }
11079                    let response = {
11080                        let bytes = common::to_bytes(body).await.unwrap_or_default();
11081                        let encoded = common::to_string(&bytes);
11082                        match serde_json::from_str(&encoded) {
11083                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
11084                            Err(error) => {
11085                                dlg.response_json_decode_error(&encoded, &error);
11086                                return Err(common::Error::JsonDecodeError(
11087                                    encoded.to_string(),
11088                                    error,
11089                                ));
11090                            }
11091                        }
11092                    };
11093
11094                    dlg.finished(true);
11095                    return Ok(response);
11096                }
11097            }
11098        }
11099    }
11100
11101    ///
11102    /// Sets the *request* property to the given value.
11103    ///
11104    /// Even though the property as already been set when instantiating this call,
11105    /// we provide this method for API completeness.
11106    pub fn request(mut self, new_value: ModifyMessageRequest) -> UserMessageModifyCall<'a, C> {
11107        self._request = new_value;
11108        self
11109    }
11110    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
11111    ///
11112    /// Sets the *user id* path property to the given value.
11113    ///
11114    /// Even though the property as already been set when instantiating this call,
11115    /// we provide this method for API completeness.
11116    pub fn user_id(mut self, new_value: &str) -> UserMessageModifyCall<'a, C> {
11117        self._user_id = new_value.to_string();
11118        self
11119    }
11120    /// The ID of the message to modify.
11121    ///
11122    /// Sets the *id* path property to the given value.
11123    ///
11124    /// Even though the property as already been set when instantiating this call,
11125    /// we provide this method for API completeness.
11126    pub fn id(mut self, new_value: &str) -> UserMessageModifyCall<'a, C> {
11127        self._id = new_value.to_string();
11128        self
11129    }
11130    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
11131    /// while executing the actual API request.
11132    ///
11133    /// ````text
11134    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
11135    /// ````
11136    ///
11137    /// Sets the *delegate* property to the given value.
11138    pub fn delegate(
11139        mut self,
11140        new_value: &'a mut dyn common::Delegate,
11141    ) -> UserMessageModifyCall<'a, C> {
11142        self._delegate = Some(new_value);
11143        self
11144    }
11145
11146    /// Set any additional parameter of the query string used in the request.
11147    /// It should be used to set parameters which are not yet available through their own
11148    /// setters.
11149    ///
11150    /// Please note that this method must not be used to set any of the known parameters
11151    /// which have their own setter method. If done anyway, the request will fail.
11152    ///
11153    /// # Additional Parameters
11154    ///
11155    /// * *$.xgafv* (query-string) - V1 error format.
11156    /// * *access_token* (query-string) - OAuth access token.
11157    /// * *alt* (query-string) - Data format for response.
11158    /// * *callback* (query-string) - JSONP
11159    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
11160    /// * *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.
11161    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
11162    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
11163    /// * *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.
11164    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
11165    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
11166    pub fn param<T>(mut self, name: T, value: T) -> UserMessageModifyCall<'a, C>
11167    where
11168        T: AsRef<str>,
11169    {
11170        self._additional_params
11171            .insert(name.as_ref().to_string(), value.as_ref().to_string());
11172        self
11173    }
11174
11175    /// Identifies the authorization scope for the method you are building.
11176    ///
11177    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
11178    /// [`Scope::Gmai`].
11179    ///
11180    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
11181    /// tokens for more than one scope.
11182    ///
11183    /// Usually there is more than one suitable scope to authorize an operation, some of which may
11184    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
11185    /// sufficient, a read-write scope will do as well.
11186    pub fn add_scope<St>(mut self, scope: St) -> UserMessageModifyCall<'a, C>
11187    where
11188        St: AsRef<str>,
11189    {
11190        self._scopes.insert(String::from(scope.as_ref()));
11191        self
11192    }
11193    /// Identifies the authorization scope(s) for the method you are building.
11194    ///
11195    /// See [`Self::add_scope()`] for details.
11196    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserMessageModifyCall<'a, C>
11197    where
11198        I: IntoIterator<Item = St>,
11199        St: AsRef<str>,
11200    {
11201        self._scopes
11202            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
11203        self
11204    }
11205
11206    /// Removes all scopes, and no default scope will be used either.
11207    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
11208    /// for details).
11209    pub fn clear_scopes(mut self) -> UserMessageModifyCall<'a, C> {
11210        self._scopes.clear();
11211        self
11212    }
11213}
11214
11215/// Sends the specified message to the recipients in the `To`, `Cc`, and `Bcc` headers. For example usage, see [Sending email](https://developers.google.com/gmail/api/guides/sending).
11216///
11217/// A builder for the *messages.send* method supported by a *user* resource.
11218/// It is not used directly, but through a [`UserMethods`] instance.
11219///
11220/// # Example
11221///
11222/// Instantiate a resource method builder
11223///
11224/// ```test_harness,no_run
11225/// # extern crate hyper;
11226/// # extern crate hyper_rustls;
11227/// # extern crate google_gmail1 as gmail1;
11228/// use gmail1::api::Message;
11229/// use std::fs;
11230/// # async fn dox() {
11231/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
11232///
11233/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
11234/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
11235/// #     secret,
11236/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
11237/// # ).build().await.unwrap();
11238///
11239/// # let client = hyper_util::client::legacy::Client::builder(
11240/// #     hyper_util::rt::TokioExecutor::new()
11241/// # )
11242/// # .build(
11243/// #     hyper_rustls::HttpsConnectorBuilder::new()
11244/// #         .with_native_roots()
11245/// #         .unwrap()
11246/// #         .https_or_http()
11247/// #         .enable_http1()
11248/// #         .build()
11249/// # );
11250/// # let mut hub = Gmail::new(client, auth);
11251/// // As the method needs a request, you would usually fill it with the desired information
11252/// // into the respective structure. Some of the parts shown here might not be applicable !
11253/// // Values shown here are possibly random and not representative !
11254/// let mut req = Message::default();
11255///
11256/// // You can configure optional parameters by calling the respective setters at will, and
11257/// // execute the final call using `upload_resumable(...)`.
11258/// // Values shown here are possibly random and not representative !
11259/// let result = hub.users().messages_send(req, "userId")
11260///              .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()).await;
11261/// # }
11262/// ```
11263pub struct UserMessageSendCall<'a, C>
11264where
11265    C: 'a,
11266{
11267    hub: &'a Gmail<C>,
11268    _request: Message,
11269    _user_id: String,
11270    _delegate: Option<&'a mut dyn common::Delegate>,
11271    _additional_params: HashMap<String, String>,
11272    _scopes: BTreeSet<String>,
11273}
11274
11275impl<'a, C> common::CallBuilder for UserMessageSendCall<'a, C> {}
11276
11277impl<'a, C> UserMessageSendCall<'a, C>
11278where
11279    C: common::Connector,
11280{
11281    /// Perform the operation you have build so far.
11282    async fn doit<RS>(
11283        mut self,
11284        mut reader: RS,
11285        reader_mime_type: mime::Mime,
11286        protocol: common::UploadProtocol,
11287    ) -> common::Result<(common::Response, Message)>
11288    where
11289        RS: common::ReadSeek,
11290    {
11291        use std::borrow::Cow;
11292        use std::io::{Read, Seek};
11293
11294        use common::{url::Params, ToParts};
11295        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
11296
11297        let mut dd = common::DefaultDelegate;
11298        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
11299        dlg.begin(common::MethodInfo {
11300            id: "gmail.users.messages.send",
11301            http_method: hyper::Method::POST,
11302        });
11303
11304        for &field in ["alt", "userId"].iter() {
11305            if self._additional_params.contains_key(field) {
11306                dlg.finished(false);
11307                return Err(common::Error::FieldClash(field));
11308            }
11309        }
11310
11311        let mut params = Params::with_capacity(4 + self._additional_params.len());
11312        params.push("userId", self._user_id);
11313
11314        params.extend(self._additional_params.iter());
11315
11316        params.push("alt", "json");
11317        let (mut url, upload_type) = if protocol == common::UploadProtocol::Resumable {
11318            (
11319                self.hub._root_url.clone()
11320                    + "resumable/upload/gmail/v1/users/{userId}/messages/send",
11321                "resumable",
11322            )
11323        } else if protocol == common::UploadProtocol::Simple {
11324            (
11325                self.hub._root_url.clone() + "upload/gmail/v1/users/{userId}/messages/send",
11326                "multipart",
11327            )
11328        } else {
11329            unreachable!()
11330        };
11331        params.push("uploadType", upload_type);
11332        if self._scopes.is_empty() {
11333            self._scopes.insert(Scope::Gmai.as_ref().to_string());
11334        }
11335
11336        #[allow(clippy::single_element_loop)]
11337        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
11338            url = params.uri_replacement(url, param_name, find_this, false);
11339        }
11340        {
11341            let to_remove = ["userId"];
11342            params.remove_params(&to_remove);
11343        }
11344
11345        let url = params.parse_with_url(&url);
11346
11347        let mut json_mime_type = mime::APPLICATION_JSON;
11348        let mut request_value_reader = {
11349            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
11350            common::remove_json_null_values(&mut value);
11351            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
11352            serde_json::to_writer(&mut dst, &value).unwrap();
11353            dst
11354        };
11355        let request_size = request_value_reader
11356            .seek(std::io::SeekFrom::End(0))
11357            .unwrap();
11358        request_value_reader
11359            .seek(std::io::SeekFrom::Start(0))
11360            .unwrap();
11361
11362        let mut upload_url_from_server;
11363
11364        loop {
11365            let token = match self
11366                .hub
11367                .auth
11368                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
11369                .await
11370            {
11371                Ok(token) => token,
11372                Err(e) => match dlg.token(e) {
11373                    Ok(token) => token,
11374                    Err(e) => {
11375                        dlg.finished(false);
11376                        return Err(common::Error::MissingToken(e));
11377                    }
11378                },
11379            };
11380            request_value_reader
11381                .seek(std::io::SeekFrom::Start(0))
11382                .unwrap();
11383            let mut req_result = {
11384                let mut mp_reader: common::MultiPartReader = Default::default();
11385                let (mut body_reader, content_type) = match protocol {
11386                    common::UploadProtocol::Simple => {
11387                        mp_reader.reserve_exact(2);
11388                        let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
11389                        reader.seek(std::io::SeekFrom::Start(0)).unwrap();
11390                        if size > 36700160 {
11391                            return Err(common::Error::UploadSizeLimitExceeded(size, 36700160));
11392                        }
11393                        mp_reader
11394                            .add_part(
11395                                &mut request_value_reader,
11396                                request_size,
11397                                json_mime_type.clone(),
11398                            )
11399                            .add_part(&mut reader, size, reader_mime_type.clone());
11400                        (
11401                            &mut mp_reader as &mut (dyn std::io::Read + Send),
11402                            common::MultiPartReader::mime_type(),
11403                        )
11404                    }
11405                    _ => (
11406                        &mut request_value_reader as &mut (dyn std::io::Read + Send),
11407                        json_mime_type.clone(),
11408                    ),
11409                };
11410                let client = &self.hub.client;
11411                dlg.pre_request();
11412                let mut req_builder = hyper::Request::builder()
11413                    .method(hyper::Method::POST)
11414                    .uri(url.as_str())
11415                    .header(USER_AGENT, self.hub._user_agent.clone());
11416
11417                if let Some(token) = token.as_ref() {
11418                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
11419                }
11420
11421                upload_url_from_server = true;
11422                if protocol == common::UploadProtocol::Resumable {
11423                    req_builder = req_builder
11424                        .header("X-Upload-Content-Type", format!("{}", reader_mime_type));
11425                }
11426
11427                let mut body_reader_bytes = vec![];
11428                body_reader.read_to_end(&mut body_reader_bytes).unwrap();
11429                let request = req_builder
11430                    .header(CONTENT_TYPE, content_type.to_string())
11431                    .body(common::to_body(body_reader_bytes.into()));
11432
11433                client.request(request.unwrap()).await
11434            };
11435
11436            match req_result {
11437                Err(err) => {
11438                    if let common::Retry::After(d) = dlg.http_error(&err) {
11439                        sleep(d).await;
11440                        continue;
11441                    }
11442                    dlg.finished(false);
11443                    return Err(common::Error::HttpError(err));
11444                }
11445                Ok(res) => {
11446                    let (mut parts, body) = res.into_parts();
11447                    let mut body = common::Body::new(body);
11448                    if !parts.status.is_success() {
11449                        let bytes = common::to_bytes(body).await.unwrap_or_default();
11450                        let error = serde_json::from_str(&common::to_string(&bytes));
11451                        let response = common::to_response(parts, bytes.into());
11452
11453                        if let common::Retry::After(d) =
11454                            dlg.http_failure(&response, error.as_ref().ok())
11455                        {
11456                            sleep(d).await;
11457                            continue;
11458                        }
11459
11460                        dlg.finished(false);
11461
11462                        return Err(match error {
11463                            Ok(value) => common::Error::BadRequest(value),
11464                            _ => common::Error::Failure(response),
11465                        });
11466                    }
11467                    if protocol == common::UploadProtocol::Resumable {
11468                        let size = reader.seek(std::io::SeekFrom::End(0)).unwrap();
11469                        reader.seek(std::io::SeekFrom::Start(0)).unwrap();
11470                        if size > 36700160 {
11471                            return Err(common::Error::UploadSizeLimitExceeded(size, 36700160));
11472                        }
11473                        let upload_result = {
11474                            let url_str = &parts
11475                                .headers
11476                                .get("Location")
11477                                .expect("LOCATION header is part of protocol")
11478                                .to_str()
11479                                .unwrap();
11480                            if upload_url_from_server {
11481                                dlg.store_upload_url(Some(url_str));
11482                            }
11483
11484                            common::ResumableUploadHelper {
11485                                client: &self.hub.client,
11486                                delegate: dlg,
11487                                start_at: if upload_url_from_server {
11488                                    Some(0)
11489                                } else {
11490                                    None
11491                                },
11492                                auth: &self.hub.auth,
11493                                user_agent: &self.hub._user_agent,
11494                                // TODO: Check this assumption
11495                                auth_header: format!(
11496                                    "Bearer {}",
11497                                    token
11498                                        .ok_or_else(|| common::Error::MissingToken(
11499                                            "resumable upload requires token".into()
11500                                        ))?
11501                                        .as_str()
11502                                ),
11503                                url: url_str,
11504                                reader: &mut reader,
11505                                media_type: reader_mime_type.clone(),
11506                                content_length: size,
11507                            }
11508                            .upload()
11509                            .await
11510                        };
11511                        match upload_result {
11512                            None => {
11513                                dlg.finished(false);
11514                                return Err(common::Error::Cancelled);
11515                            }
11516                            Some(Err(err)) => {
11517                                dlg.finished(false);
11518                                return Err(common::Error::HttpError(err));
11519                            }
11520                            Some(Ok(response)) => {
11521                                (parts, body) = response.into_parts();
11522                                if !parts.status.is_success() {
11523                                    dlg.store_upload_url(None);
11524                                    dlg.finished(false);
11525                                    return Err(common::Error::Failure(
11526                                        common::Response::from_parts(parts, body),
11527                                    ));
11528                                }
11529                            }
11530                        }
11531                    }
11532                    let response = {
11533                        let bytes = common::to_bytes(body).await.unwrap_or_default();
11534                        let encoded = common::to_string(&bytes);
11535                        match serde_json::from_str(&encoded) {
11536                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
11537                            Err(error) => {
11538                                dlg.response_json_decode_error(&encoded, &error);
11539                                return Err(common::Error::JsonDecodeError(
11540                                    encoded.to_string(),
11541                                    error,
11542                                ));
11543                            }
11544                        }
11545                    };
11546
11547                    dlg.finished(true);
11548                    return Ok(response);
11549                }
11550            }
11551        }
11552    }
11553
11554    /// Upload media in a resumable fashion.
11555    /// Even if the upload fails or is interrupted, it can be resumed for a
11556    /// certain amount of time as the server maintains state temporarily.
11557    ///
11558    /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL
11559    /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate
11560    /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using
11561    /// `cancel_chunk_upload(...)`.
11562    ///
11563    /// * *multipart*: yes
11564    /// * *max size*: 36700160
11565    /// * *valid mime types*: 'message/*'
11566    pub async fn upload_resumable<RS>(
11567        self,
11568        resumeable_stream: RS,
11569        mime_type: mime::Mime,
11570    ) -> common::Result<(common::Response, Message)>
11571    where
11572        RS: common::ReadSeek,
11573    {
11574        self.doit(
11575            resumeable_stream,
11576            mime_type,
11577            common::UploadProtocol::Resumable,
11578        )
11579        .await
11580    }
11581    /// Upload media all at once.
11582    /// If the upload fails for whichever reason, all progress is lost.
11583    ///
11584    /// * *multipart*: yes
11585    /// * *max size*: 36700160
11586    /// * *valid mime types*: 'message/*'
11587    pub async fn upload<RS>(
11588        self,
11589        stream: RS,
11590        mime_type: mime::Mime,
11591    ) -> common::Result<(common::Response, Message)>
11592    where
11593        RS: common::ReadSeek,
11594    {
11595        self.doit(stream, mime_type, common::UploadProtocol::Simple)
11596            .await
11597    }
11598
11599    ///
11600    /// Sets the *request* property to the given value.
11601    ///
11602    /// Even though the property as already been set when instantiating this call,
11603    /// we provide this method for API completeness.
11604    pub fn request(mut self, new_value: Message) -> UserMessageSendCall<'a, C> {
11605        self._request = new_value;
11606        self
11607    }
11608    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
11609    ///
11610    /// Sets the *user id* path property to the given value.
11611    ///
11612    /// Even though the property as already been set when instantiating this call,
11613    /// we provide this method for API completeness.
11614    pub fn user_id(mut self, new_value: &str) -> UserMessageSendCall<'a, C> {
11615        self._user_id = new_value.to_string();
11616        self
11617    }
11618    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
11619    /// while executing the actual API request.
11620    ///
11621    /// ````text
11622    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
11623    /// ````
11624    ///
11625    /// Sets the *delegate* property to the given value.
11626    pub fn delegate(
11627        mut self,
11628        new_value: &'a mut dyn common::Delegate,
11629    ) -> UserMessageSendCall<'a, C> {
11630        self._delegate = Some(new_value);
11631        self
11632    }
11633
11634    /// Set any additional parameter of the query string used in the request.
11635    /// It should be used to set parameters which are not yet available through their own
11636    /// setters.
11637    ///
11638    /// Please note that this method must not be used to set any of the known parameters
11639    /// which have their own setter method. If done anyway, the request will fail.
11640    ///
11641    /// # Additional Parameters
11642    ///
11643    /// * *$.xgafv* (query-string) - V1 error format.
11644    /// * *access_token* (query-string) - OAuth access token.
11645    /// * *alt* (query-string) - Data format for response.
11646    /// * *callback* (query-string) - JSONP
11647    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
11648    /// * *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.
11649    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
11650    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
11651    /// * *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.
11652    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
11653    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
11654    pub fn param<T>(mut self, name: T, value: T) -> UserMessageSendCall<'a, C>
11655    where
11656        T: AsRef<str>,
11657    {
11658        self._additional_params
11659            .insert(name.as_ref().to_string(), value.as_ref().to_string());
11660        self
11661    }
11662
11663    /// Identifies the authorization scope for the method you are building.
11664    ///
11665    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
11666    /// [`Scope::Gmai`].
11667    ///
11668    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
11669    /// tokens for more than one scope.
11670    ///
11671    /// Usually there is more than one suitable scope to authorize an operation, some of which may
11672    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
11673    /// sufficient, a read-write scope will do as well.
11674    pub fn add_scope<St>(mut self, scope: St) -> UserMessageSendCall<'a, C>
11675    where
11676        St: AsRef<str>,
11677    {
11678        self._scopes.insert(String::from(scope.as_ref()));
11679        self
11680    }
11681    /// Identifies the authorization scope(s) for the method you are building.
11682    ///
11683    /// See [`Self::add_scope()`] for details.
11684    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserMessageSendCall<'a, C>
11685    where
11686        I: IntoIterator<Item = St>,
11687        St: AsRef<str>,
11688    {
11689        self._scopes
11690            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
11691        self
11692    }
11693
11694    /// Removes all scopes, and no default scope will be used either.
11695    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
11696    /// for details).
11697    pub fn clear_scopes(mut self) -> UserMessageSendCall<'a, C> {
11698        self._scopes.clear();
11699        self
11700    }
11701}
11702
11703/// Moves the specified message to the trash.
11704///
11705/// A builder for the *messages.trash* method supported by a *user* resource.
11706/// It is not used directly, but through a [`UserMethods`] instance.
11707///
11708/// # Example
11709///
11710/// Instantiate a resource method builder
11711///
11712/// ```test_harness,no_run
11713/// # extern crate hyper;
11714/// # extern crate hyper_rustls;
11715/// # extern crate google_gmail1 as gmail1;
11716/// # async fn dox() {
11717/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
11718///
11719/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
11720/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
11721/// #     secret,
11722/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
11723/// # ).build().await.unwrap();
11724///
11725/// # let client = hyper_util::client::legacy::Client::builder(
11726/// #     hyper_util::rt::TokioExecutor::new()
11727/// # )
11728/// # .build(
11729/// #     hyper_rustls::HttpsConnectorBuilder::new()
11730/// #         .with_native_roots()
11731/// #         .unwrap()
11732/// #         .https_or_http()
11733/// #         .enable_http1()
11734/// #         .build()
11735/// # );
11736/// # let mut hub = Gmail::new(client, auth);
11737/// // You can configure optional parameters by calling the respective setters at will, and
11738/// // execute the final call using `doit()`.
11739/// // Values shown here are possibly random and not representative !
11740/// let result = hub.users().messages_trash("userId", "id")
11741///              .doit().await;
11742/// # }
11743/// ```
11744pub struct UserMessageTrashCall<'a, C>
11745where
11746    C: 'a,
11747{
11748    hub: &'a Gmail<C>,
11749    _user_id: String,
11750    _id: String,
11751    _delegate: Option<&'a mut dyn common::Delegate>,
11752    _additional_params: HashMap<String, String>,
11753    _scopes: BTreeSet<String>,
11754}
11755
11756impl<'a, C> common::CallBuilder for UserMessageTrashCall<'a, C> {}
11757
11758impl<'a, C> UserMessageTrashCall<'a, C>
11759where
11760    C: common::Connector,
11761{
11762    /// Perform the operation you have build so far.
11763    pub async fn doit(mut self) -> common::Result<(common::Response, Message)> {
11764        use std::borrow::Cow;
11765        use std::io::{Read, Seek};
11766
11767        use common::{url::Params, ToParts};
11768        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
11769
11770        let mut dd = common::DefaultDelegate;
11771        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
11772        dlg.begin(common::MethodInfo {
11773            id: "gmail.users.messages.trash",
11774            http_method: hyper::Method::POST,
11775        });
11776
11777        for &field in ["alt", "userId", "id"].iter() {
11778            if self._additional_params.contains_key(field) {
11779                dlg.finished(false);
11780                return Err(common::Error::FieldClash(field));
11781            }
11782        }
11783
11784        let mut params = Params::with_capacity(4 + self._additional_params.len());
11785        params.push("userId", self._user_id);
11786        params.push("id", self._id);
11787
11788        params.extend(self._additional_params.iter());
11789
11790        params.push("alt", "json");
11791        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/messages/{id}/trash";
11792        if self._scopes.is_empty() {
11793            self._scopes.insert(Scope::Gmai.as_ref().to_string());
11794        }
11795
11796        #[allow(clippy::single_element_loop)]
11797        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
11798            url = params.uri_replacement(url, param_name, find_this, false);
11799        }
11800        {
11801            let to_remove = ["id", "userId"];
11802            params.remove_params(&to_remove);
11803        }
11804
11805        let url = params.parse_with_url(&url);
11806
11807        loop {
11808            let token = match self
11809                .hub
11810                .auth
11811                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
11812                .await
11813            {
11814                Ok(token) => token,
11815                Err(e) => match dlg.token(e) {
11816                    Ok(token) => token,
11817                    Err(e) => {
11818                        dlg.finished(false);
11819                        return Err(common::Error::MissingToken(e));
11820                    }
11821                },
11822            };
11823            let mut req_result = {
11824                let client = &self.hub.client;
11825                dlg.pre_request();
11826                let mut req_builder = hyper::Request::builder()
11827                    .method(hyper::Method::POST)
11828                    .uri(url.as_str())
11829                    .header(USER_AGENT, self.hub._user_agent.clone());
11830
11831                if let Some(token) = token.as_ref() {
11832                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
11833                }
11834
11835                let request = req_builder
11836                    .header(CONTENT_LENGTH, 0_u64)
11837                    .body(common::to_body::<String>(None));
11838
11839                client.request(request.unwrap()).await
11840            };
11841
11842            match req_result {
11843                Err(err) => {
11844                    if let common::Retry::After(d) = dlg.http_error(&err) {
11845                        sleep(d).await;
11846                        continue;
11847                    }
11848                    dlg.finished(false);
11849                    return Err(common::Error::HttpError(err));
11850                }
11851                Ok(res) => {
11852                    let (mut parts, body) = res.into_parts();
11853                    let mut body = common::Body::new(body);
11854                    if !parts.status.is_success() {
11855                        let bytes = common::to_bytes(body).await.unwrap_or_default();
11856                        let error = serde_json::from_str(&common::to_string(&bytes));
11857                        let response = common::to_response(parts, bytes.into());
11858
11859                        if let common::Retry::After(d) =
11860                            dlg.http_failure(&response, error.as_ref().ok())
11861                        {
11862                            sleep(d).await;
11863                            continue;
11864                        }
11865
11866                        dlg.finished(false);
11867
11868                        return Err(match error {
11869                            Ok(value) => common::Error::BadRequest(value),
11870                            _ => common::Error::Failure(response),
11871                        });
11872                    }
11873                    let response = {
11874                        let bytes = common::to_bytes(body).await.unwrap_or_default();
11875                        let encoded = common::to_string(&bytes);
11876                        match serde_json::from_str(&encoded) {
11877                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
11878                            Err(error) => {
11879                                dlg.response_json_decode_error(&encoded, &error);
11880                                return Err(common::Error::JsonDecodeError(
11881                                    encoded.to_string(),
11882                                    error,
11883                                ));
11884                            }
11885                        }
11886                    };
11887
11888                    dlg.finished(true);
11889                    return Ok(response);
11890                }
11891            }
11892        }
11893    }
11894
11895    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
11896    ///
11897    /// Sets the *user id* path property to the given value.
11898    ///
11899    /// Even though the property as already been set when instantiating this call,
11900    /// we provide this method for API completeness.
11901    pub fn user_id(mut self, new_value: &str) -> UserMessageTrashCall<'a, C> {
11902        self._user_id = new_value.to_string();
11903        self
11904    }
11905    /// The ID of the message to Trash.
11906    ///
11907    /// Sets the *id* path property to the given value.
11908    ///
11909    /// Even though the property as already been set when instantiating this call,
11910    /// we provide this method for API completeness.
11911    pub fn id(mut self, new_value: &str) -> UserMessageTrashCall<'a, C> {
11912        self._id = new_value.to_string();
11913        self
11914    }
11915    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
11916    /// while executing the actual API request.
11917    ///
11918    /// ````text
11919    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
11920    /// ````
11921    ///
11922    /// Sets the *delegate* property to the given value.
11923    pub fn delegate(
11924        mut self,
11925        new_value: &'a mut dyn common::Delegate,
11926    ) -> UserMessageTrashCall<'a, C> {
11927        self._delegate = Some(new_value);
11928        self
11929    }
11930
11931    /// Set any additional parameter of the query string used in the request.
11932    /// It should be used to set parameters which are not yet available through their own
11933    /// setters.
11934    ///
11935    /// Please note that this method must not be used to set any of the known parameters
11936    /// which have their own setter method. If done anyway, the request will fail.
11937    ///
11938    /// # Additional Parameters
11939    ///
11940    /// * *$.xgafv* (query-string) - V1 error format.
11941    /// * *access_token* (query-string) - OAuth access token.
11942    /// * *alt* (query-string) - Data format for response.
11943    /// * *callback* (query-string) - JSONP
11944    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
11945    /// * *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.
11946    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
11947    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
11948    /// * *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.
11949    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
11950    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
11951    pub fn param<T>(mut self, name: T, value: T) -> UserMessageTrashCall<'a, C>
11952    where
11953        T: AsRef<str>,
11954    {
11955        self._additional_params
11956            .insert(name.as_ref().to_string(), value.as_ref().to_string());
11957        self
11958    }
11959
11960    /// Identifies the authorization scope for the method you are building.
11961    ///
11962    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
11963    /// [`Scope::Gmai`].
11964    ///
11965    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
11966    /// tokens for more than one scope.
11967    ///
11968    /// Usually there is more than one suitable scope to authorize an operation, some of which may
11969    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
11970    /// sufficient, a read-write scope will do as well.
11971    pub fn add_scope<St>(mut self, scope: St) -> UserMessageTrashCall<'a, C>
11972    where
11973        St: AsRef<str>,
11974    {
11975        self._scopes.insert(String::from(scope.as_ref()));
11976        self
11977    }
11978    /// Identifies the authorization scope(s) for the method you are building.
11979    ///
11980    /// See [`Self::add_scope()`] for details.
11981    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserMessageTrashCall<'a, C>
11982    where
11983        I: IntoIterator<Item = St>,
11984        St: AsRef<str>,
11985    {
11986        self._scopes
11987            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
11988        self
11989    }
11990
11991    /// Removes all scopes, and no default scope will be used either.
11992    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
11993    /// for details).
11994    pub fn clear_scopes(mut self) -> UserMessageTrashCall<'a, C> {
11995        self._scopes.clear();
11996        self
11997    }
11998}
11999
12000/// Removes the specified message from the trash.
12001///
12002/// A builder for the *messages.untrash* method supported by a *user* resource.
12003/// It is not used directly, but through a [`UserMethods`] instance.
12004///
12005/// # Example
12006///
12007/// Instantiate a resource method builder
12008///
12009/// ```test_harness,no_run
12010/// # extern crate hyper;
12011/// # extern crate hyper_rustls;
12012/// # extern crate google_gmail1 as gmail1;
12013/// # async fn dox() {
12014/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
12015///
12016/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
12017/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
12018/// #     secret,
12019/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
12020/// # ).build().await.unwrap();
12021///
12022/// # let client = hyper_util::client::legacy::Client::builder(
12023/// #     hyper_util::rt::TokioExecutor::new()
12024/// # )
12025/// # .build(
12026/// #     hyper_rustls::HttpsConnectorBuilder::new()
12027/// #         .with_native_roots()
12028/// #         .unwrap()
12029/// #         .https_or_http()
12030/// #         .enable_http1()
12031/// #         .build()
12032/// # );
12033/// # let mut hub = Gmail::new(client, auth);
12034/// // You can configure optional parameters by calling the respective setters at will, and
12035/// // execute the final call using `doit()`.
12036/// // Values shown here are possibly random and not representative !
12037/// let result = hub.users().messages_untrash("userId", "id")
12038///              .doit().await;
12039/// # }
12040/// ```
12041pub struct UserMessageUntrashCall<'a, C>
12042where
12043    C: 'a,
12044{
12045    hub: &'a Gmail<C>,
12046    _user_id: String,
12047    _id: String,
12048    _delegate: Option<&'a mut dyn common::Delegate>,
12049    _additional_params: HashMap<String, String>,
12050    _scopes: BTreeSet<String>,
12051}
12052
12053impl<'a, C> common::CallBuilder for UserMessageUntrashCall<'a, C> {}
12054
12055impl<'a, C> UserMessageUntrashCall<'a, C>
12056where
12057    C: common::Connector,
12058{
12059    /// Perform the operation you have build so far.
12060    pub async fn doit(mut self) -> common::Result<(common::Response, Message)> {
12061        use std::borrow::Cow;
12062        use std::io::{Read, Seek};
12063
12064        use common::{url::Params, ToParts};
12065        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
12066
12067        let mut dd = common::DefaultDelegate;
12068        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
12069        dlg.begin(common::MethodInfo {
12070            id: "gmail.users.messages.untrash",
12071            http_method: hyper::Method::POST,
12072        });
12073
12074        for &field in ["alt", "userId", "id"].iter() {
12075            if self._additional_params.contains_key(field) {
12076                dlg.finished(false);
12077                return Err(common::Error::FieldClash(field));
12078            }
12079        }
12080
12081        let mut params = Params::with_capacity(4 + self._additional_params.len());
12082        params.push("userId", self._user_id);
12083        params.push("id", self._id);
12084
12085        params.extend(self._additional_params.iter());
12086
12087        params.push("alt", "json");
12088        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/messages/{id}/untrash";
12089        if self._scopes.is_empty() {
12090            self._scopes.insert(Scope::Gmai.as_ref().to_string());
12091        }
12092
12093        #[allow(clippy::single_element_loop)]
12094        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
12095            url = params.uri_replacement(url, param_name, find_this, false);
12096        }
12097        {
12098            let to_remove = ["id", "userId"];
12099            params.remove_params(&to_remove);
12100        }
12101
12102        let url = params.parse_with_url(&url);
12103
12104        loop {
12105            let token = match self
12106                .hub
12107                .auth
12108                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
12109                .await
12110            {
12111                Ok(token) => token,
12112                Err(e) => match dlg.token(e) {
12113                    Ok(token) => token,
12114                    Err(e) => {
12115                        dlg.finished(false);
12116                        return Err(common::Error::MissingToken(e));
12117                    }
12118                },
12119            };
12120            let mut req_result = {
12121                let client = &self.hub.client;
12122                dlg.pre_request();
12123                let mut req_builder = hyper::Request::builder()
12124                    .method(hyper::Method::POST)
12125                    .uri(url.as_str())
12126                    .header(USER_AGENT, self.hub._user_agent.clone());
12127
12128                if let Some(token) = token.as_ref() {
12129                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
12130                }
12131
12132                let request = req_builder
12133                    .header(CONTENT_LENGTH, 0_u64)
12134                    .body(common::to_body::<String>(None));
12135
12136                client.request(request.unwrap()).await
12137            };
12138
12139            match req_result {
12140                Err(err) => {
12141                    if let common::Retry::After(d) = dlg.http_error(&err) {
12142                        sleep(d).await;
12143                        continue;
12144                    }
12145                    dlg.finished(false);
12146                    return Err(common::Error::HttpError(err));
12147                }
12148                Ok(res) => {
12149                    let (mut parts, body) = res.into_parts();
12150                    let mut body = common::Body::new(body);
12151                    if !parts.status.is_success() {
12152                        let bytes = common::to_bytes(body).await.unwrap_or_default();
12153                        let error = serde_json::from_str(&common::to_string(&bytes));
12154                        let response = common::to_response(parts, bytes.into());
12155
12156                        if let common::Retry::After(d) =
12157                            dlg.http_failure(&response, error.as_ref().ok())
12158                        {
12159                            sleep(d).await;
12160                            continue;
12161                        }
12162
12163                        dlg.finished(false);
12164
12165                        return Err(match error {
12166                            Ok(value) => common::Error::BadRequest(value),
12167                            _ => common::Error::Failure(response),
12168                        });
12169                    }
12170                    let response = {
12171                        let bytes = common::to_bytes(body).await.unwrap_or_default();
12172                        let encoded = common::to_string(&bytes);
12173                        match serde_json::from_str(&encoded) {
12174                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
12175                            Err(error) => {
12176                                dlg.response_json_decode_error(&encoded, &error);
12177                                return Err(common::Error::JsonDecodeError(
12178                                    encoded.to_string(),
12179                                    error,
12180                                ));
12181                            }
12182                        }
12183                    };
12184
12185                    dlg.finished(true);
12186                    return Ok(response);
12187                }
12188            }
12189        }
12190    }
12191
12192    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
12193    ///
12194    /// Sets the *user id* path property to the given value.
12195    ///
12196    /// Even though the property as already been set when instantiating this call,
12197    /// we provide this method for API completeness.
12198    pub fn user_id(mut self, new_value: &str) -> UserMessageUntrashCall<'a, C> {
12199        self._user_id = new_value.to_string();
12200        self
12201    }
12202    /// The ID of the message to remove from Trash.
12203    ///
12204    /// Sets the *id* path property to the given value.
12205    ///
12206    /// Even though the property as already been set when instantiating this call,
12207    /// we provide this method for API completeness.
12208    pub fn id(mut self, new_value: &str) -> UserMessageUntrashCall<'a, C> {
12209        self._id = new_value.to_string();
12210        self
12211    }
12212    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
12213    /// while executing the actual API request.
12214    ///
12215    /// ````text
12216    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
12217    /// ````
12218    ///
12219    /// Sets the *delegate* property to the given value.
12220    pub fn delegate(
12221        mut self,
12222        new_value: &'a mut dyn common::Delegate,
12223    ) -> UserMessageUntrashCall<'a, C> {
12224        self._delegate = Some(new_value);
12225        self
12226    }
12227
12228    /// Set any additional parameter of the query string used in the request.
12229    /// It should be used to set parameters which are not yet available through their own
12230    /// setters.
12231    ///
12232    /// Please note that this method must not be used to set any of the known parameters
12233    /// which have their own setter method. If done anyway, the request will fail.
12234    ///
12235    /// # Additional Parameters
12236    ///
12237    /// * *$.xgafv* (query-string) - V1 error format.
12238    /// * *access_token* (query-string) - OAuth access token.
12239    /// * *alt* (query-string) - Data format for response.
12240    /// * *callback* (query-string) - JSONP
12241    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
12242    /// * *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.
12243    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
12244    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
12245    /// * *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.
12246    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
12247    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
12248    pub fn param<T>(mut self, name: T, value: T) -> UserMessageUntrashCall<'a, C>
12249    where
12250        T: AsRef<str>,
12251    {
12252        self._additional_params
12253            .insert(name.as_ref().to_string(), value.as_ref().to_string());
12254        self
12255    }
12256
12257    /// Identifies the authorization scope for the method you are building.
12258    ///
12259    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
12260    /// [`Scope::Gmai`].
12261    ///
12262    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
12263    /// tokens for more than one scope.
12264    ///
12265    /// Usually there is more than one suitable scope to authorize an operation, some of which may
12266    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
12267    /// sufficient, a read-write scope will do as well.
12268    pub fn add_scope<St>(mut self, scope: St) -> UserMessageUntrashCall<'a, C>
12269    where
12270        St: AsRef<str>,
12271    {
12272        self._scopes.insert(String::from(scope.as_ref()));
12273        self
12274    }
12275    /// Identifies the authorization scope(s) for the method you are building.
12276    ///
12277    /// See [`Self::add_scope()`] for details.
12278    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserMessageUntrashCall<'a, C>
12279    where
12280        I: IntoIterator<Item = St>,
12281        St: AsRef<str>,
12282    {
12283        self._scopes
12284            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
12285        self
12286    }
12287
12288    /// Removes all scopes, and no default scope will be used either.
12289    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
12290    /// for details).
12291    pub fn clear_scopes(mut self) -> UserMessageUntrashCall<'a, C> {
12292        self._scopes.clear();
12293        self
12294    }
12295}
12296
12297/// Creates and configures a client-side encryption identity that's authorized to send mail from the user account. Google publishes the S/MIME certificate to a shared domain-wide directory so that people within a Google Workspace organization can encrypt and send mail to the identity.
12298///
12299/// A builder for the *settings.cse.identities.create* method supported by a *user* resource.
12300/// It is not used directly, but through a [`UserMethods`] instance.
12301///
12302/// # Example
12303///
12304/// Instantiate a resource method builder
12305///
12306/// ```test_harness,no_run
12307/// # extern crate hyper;
12308/// # extern crate hyper_rustls;
12309/// # extern crate google_gmail1 as gmail1;
12310/// use gmail1::api::CseIdentity;
12311/// # async fn dox() {
12312/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
12313///
12314/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
12315/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
12316/// #     secret,
12317/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
12318/// # ).build().await.unwrap();
12319///
12320/// # let client = hyper_util::client::legacy::Client::builder(
12321/// #     hyper_util::rt::TokioExecutor::new()
12322/// # )
12323/// # .build(
12324/// #     hyper_rustls::HttpsConnectorBuilder::new()
12325/// #         .with_native_roots()
12326/// #         .unwrap()
12327/// #         .https_or_http()
12328/// #         .enable_http1()
12329/// #         .build()
12330/// # );
12331/// # let mut hub = Gmail::new(client, auth);
12332/// // As the method needs a request, you would usually fill it with the desired information
12333/// // into the respective structure. Some of the parts shown here might not be applicable !
12334/// // Values shown here are possibly random and not representative !
12335/// let mut req = CseIdentity::default();
12336///
12337/// // You can configure optional parameters by calling the respective setters at will, and
12338/// // execute the final call using `doit()`.
12339/// // Values shown here are possibly random and not representative !
12340/// let result = hub.users().settings_cse_identities_create(req, "userId")
12341///              .doit().await;
12342/// # }
12343/// ```
12344pub struct UserSettingCseIdentityCreateCall<'a, C>
12345where
12346    C: 'a,
12347{
12348    hub: &'a Gmail<C>,
12349    _request: CseIdentity,
12350    _user_id: String,
12351    _delegate: Option<&'a mut dyn common::Delegate>,
12352    _additional_params: HashMap<String, String>,
12353    _scopes: BTreeSet<String>,
12354}
12355
12356impl<'a, C> common::CallBuilder for UserSettingCseIdentityCreateCall<'a, C> {}
12357
12358impl<'a, C> UserSettingCseIdentityCreateCall<'a, C>
12359where
12360    C: common::Connector,
12361{
12362    /// Perform the operation you have build so far.
12363    pub async fn doit(mut self) -> common::Result<(common::Response, CseIdentity)> {
12364        use std::borrow::Cow;
12365        use std::io::{Read, Seek};
12366
12367        use common::{url::Params, ToParts};
12368        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
12369
12370        let mut dd = common::DefaultDelegate;
12371        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
12372        dlg.begin(common::MethodInfo {
12373            id: "gmail.users.settings.cse.identities.create",
12374            http_method: hyper::Method::POST,
12375        });
12376
12377        for &field in ["alt", "userId"].iter() {
12378            if self._additional_params.contains_key(field) {
12379                dlg.finished(false);
12380                return Err(common::Error::FieldClash(field));
12381            }
12382        }
12383
12384        let mut params = Params::with_capacity(4 + self._additional_params.len());
12385        params.push("userId", self._user_id);
12386
12387        params.extend(self._additional_params.iter());
12388
12389        params.push("alt", "json");
12390        let mut url =
12391            self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/cse/identities";
12392        if self._scopes.is_empty() {
12393            self._scopes
12394                .insert(Scope::SettingBasic.as_ref().to_string());
12395        }
12396
12397        #[allow(clippy::single_element_loop)]
12398        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
12399            url = params.uri_replacement(url, param_name, find_this, false);
12400        }
12401        {
12402            let to_remove = ["userId"];
12403            params.remove_params(&to_remove);
12404        }
12405
12406        let url = params.parse_with_url(&url);
12407
12408        let mut json_mime_type = mime::APPLICATION_JSON;
12409        let mut request_value_reader = {
12410            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
12411            common::remove_json_null_values(&mut value);
12412            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
12413            serde_json::to_writer(&mut dst, &value).unwrap();
12414            dst
12415        };
12416        let request_size = request_value_reader
12417            .seek(std::io::SeekFrom::End(0))
12418            .unwrap();
12419        request_value_reader
12420            .seek(std::io::SeekFrom::Start(0))
12421            .unwrap();
12422
12423        loop {
12424            let token = match self
12425                .hub
12426                .auth
12427                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
12428                .await
12429            {
12430                Ok(token) => token,
12431                Err(e) => match dlg.token(e) {
12432                    Ok(token) => token,
12433                    Err(e) => {
12434                        dlg.finished(false);
12435                        return Err(common::Error::MissingToken(e));
12436                    }
12437                },
12438            };
12439            request_value_reader
12440                .seek(std::io::SeekFrom::Start(0))
12441                .unwrap();
12442            let mut req_result = {
12443                let client = &self.hub.client;
12444                dlg.pre_request();
12445                let mut req_builder = hyper::Request::builder()
12446                    .method(hyper::Method::POST)
12447                    .uri(url.as_str())
12448                    .header(USER_AGENT, self.hub._user_agent.clone());
12449
12450                if let Some(token) = token.as_ref() {
12451                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
12452                }
12453
12454                let request = req_builder
12455                    .header(CONTENT_TYPE, json_mime_type.to_string())
12456                    .header(CONTENT_LENGTH, request_size as u64)
12457                    .body(common::to_body(
12458                        request_value_reader.get_ref().clone().into(),
12459                    ));
12460
12461                client.request(request.unwrap()).await
12462            };
12463
12464            match req_result {
12465                Err(err) => {
12466                    if let common::Retry::After(d) = dlg.http_error(&err) {
12467                        sleep(d).await;
12468                        continue;
12469                    }
12470                    dlg.finished(false);
12471                    return Err(common::Error::HttpError(err));
12472                }
12473                Ok(res) => {
12474                    let (mut parts, body) = res.into_parts();
12475                    let mut body = common::Body::new(body);
12476                    if !parts.status.is_success() {
12477                        let bytes = common::to_bytes(body).await.unwrap_or_default();
12478                        let error = serde_json::from_str(&common::to_string(&bytes));
12479                        let response = common::to_response(parts, bytes.into());
12480
12481                        if let common::Retry::After(d) =
12482                            dlg.http_failure(&response, error.as_ref().ok())
12483                        {
12484                            sleep(d).await;
12485                            continue;
12486                        }
12487
12488                        dlg.finished(false);
12489
12490                        return Err(match error {
12491                            Ok(value) => common::Error::BadRequest(value),
12492                            _ => common::Error::Failure(response),
12493                        });
12494                    }
12495                    let response = {
12496                        let bytes = common::to_bytes(body).await.unwrap_or_default();
12497                        let encoded = common::to_string(&bytes);
12498                        match serde_json::from_str(&encoded) {
12499                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
12500                            Err(error) => {
12501                                dlg.response_json_decode_error(&encoded, &error);
12502                                return Err(common::Error::JsonDecodeError(
12503                                    encoded.to_string(),
12504                                    error,
12505                                ));
12506                            }
12507                        }
12508                    };
12509
12510                    dlg.finished(true);
12511                    return Ok(response);
12512                }
12513            }
12514        }
12515    }
12516
12517    ///
12518    /// Sets the *request* property to the given value.
12519    ///
12520    /// Even though the property as already been set when instantiating this call,
12521    /// we provide this method for API completeness.
12522    pub fn request(mut self, new_value: CseIdentity) -> UserSettingCseIdentityCreateCall<'a, C> {
12523        self._request = new_value;
12524        self
12525    }
12526    /// The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
12527    ///
12528    /// Sets the *user id* path property to the given value.
12529    ///
12530    /// Even though the property as already been set when instantiating this call,
12531    /// we provide this method for API completeness.
12532    pub fn user_id(mut self, new_value: &str) -> UserSettingCseIdentityCreateCall<'a, C> {
12533        self._user_id = new_value.to_string();
12534        self
12535    }
12536    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
12537    /// while executing the actual API request.
12538    ///
12539    /// ````text
12540    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
12541    /// ````
12542    ///
12543    /// Sets the *delegate* property to the given value.
12544    pub fn delegate(
12545        mut self,
12546        new_value: &'a mut dyn common::Delegate,
12547    ) -> UserSettingCseIdentityCreateCall<'a, C> {
12548        self._delegate = Some(new_value);
12549        self
12550    }
12551
12552    /// Set any additional parameter of the query string used in the request.
12553    /// It should be used to set parameters which are not yet available through their own
12554    /// setters.
12555    ///
12556    /// Please note that this method must not be used to set any of the known parameters
12557    /// which have their own setter method. If done anyway, the request will fail.
12558    ///
12559    /// # Additional Parameters
12560    ///
12561    /// * *$.xgafv* (query-string) - V1 error format.
12562    /// * *access_token* (query-string) - OAuth access token.
12563    /// * *alt* (query-string) - Data format for response.
12564    /// * *callback* (query-string) - JSONP
12565    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
12566    /// * *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.
12567    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
12568    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
12569    /// * *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.
12570    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
12571    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
12572    pub fn param<T>(mut self, name: T, value: T) -> UserSettingCseIdentityCreateCall<'a, C>
12573    where
12574        T: AsRef<str>,
12575    {
12576        self._additional_params
12577            .insert(name.as_ref().to_string(), value.as_ref().to_string());
12578        self
12579    }
12580
12581    /// Identifies the authorization scope for the method you are building.
12582    ///
12583    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
12584    /// [`Scope::SettingBasic`].
12585    ///
12586    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
12587    /// tokens for more than one scope.
12588    ///
12589    /// Usually there is more than one suitable scope to authorize an operation, some of which may
12590    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
12591    /// sufficient, a read-write scope will do as well.
12592    pub fn add_scope<St>(mut self, scope: St) -> UserSettingCseIdentityCreateCall<'a, C>
12593    where
12594        St: AsRef<str>,
12595    {
12596        self._scopes.insert(String::from(scope.as_ref()));
12597        self
12598    }
12599    /// Identifies the authorization scope(s) for the method you are building.
12600    ///
12601    /// See [`Self::add_scope()`] for details.
12602    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingCseIdentityCreateCall<'a, C>
12603    where
12604        I: IntoIterator<Item = St>,
12605        St: AsRef<str>,
12606    {
12607        self._scopes
12608            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
12609        self
12610    }
12611
12612    /// Removes all scopes, and no default scope will be used either.
12613    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
12614    /// for details).
12615    pub fn clear_scopes(mut self) -> UserSettingCseIdentityCreateCall<'a, C> {
12616        self._scopes.clear();
12617        self
12618    }
12619}
12620
12621/// Deletes a client-side encryption identity. The authenticated user can no longer use the identity to send encrypted messages. You cannot restore the identity after you delete it. Instead, use the CreateCseIdentity method to create another identity with the same configuration.
12622///
12623/// A builder for the *settings.cse.identities.delete* method supported by a *user* resource.
12624/// It is not used directly, but through a [`UserMethods`] instance.
12625///
12626/// # Example
12627///
12628/// Instantiate a resource method builder
12629///
12630/// ```test_harness,no_run
12631/// # extern crate hyper;
12632/// # extern crate hyper_rustls;
12633/// # extern crate google_gmail1 as gmail1;
12634/// # async fn dox() {
12635/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
12636///
12637/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
12638/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
12639/// #     secret,
12640/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
12641/// # ).build().await.unwrap();
12642///
12643/// # let client = hyper_util::client::legacy::Client::builder(
12644/// #     hyper_util::rt::TokioExecutor::new()
12645/// # )
12646/// # .build(
12647/// #     hyper_rustls::HttpsConnectorBuilder::new()
12648/// #         .with_native_roots()
12649/// #         .unwrap()
12650/// #         .https_or_http()
12651/// #         .enable_http1()
12652/// #         .build()
12653/// # );
12654/// # let mut hub = Gmail::new(client, auth);
12655/// // You can configure optional parameters by calling the respective setters at will, and
12656/// // execute the final call using `doit()`.
12657/// // Values shown here are possibly random and not representative !
12658/// let result = hub.users().settings_cse_identities_delete("userId", "cseEmailAddress")
12659///              .doit().await;
12660/// # }
12661/// ```
12662pub struct UserSettingCseIdentityDeleteCall<'a, C>
12663where
12664    C: 'a,
12665{
12666    hub: &'a Gmail<C>,
12667    _user_id: String,
12668    _cse_email_address: String,
12669    _delegate: Option<&'a mut dyn common::Delegate>,
12670    _additional_params: HashMap<String, String>,
12671    _scopes: BTreeSet<String>,
12672}
12673
12674impl<'a, C> common::CallBuilder for UserSettingCseIdentityDeleteCall<'a, C> {}
12675
12676impl<'a, C> UserSettingCseIdentityDeleteCall<'a, C>
12677where
12678    C: common::Connector,
12679{
12680    /// Perform the operation you have build so far.
12681    pub async fn doit(mut self) -> common::Result<common::Response> {
12682        use std::borrow::Cow;
12683        use std::io::{Read, Seek};
12684
12685        use common::{url::Params, ToParts};
12686        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
12687
12688        let mut dd = common::DefaultDelegate;
12689        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
12690        dlg.begin(common::MethodInfo {
12691            id: "gmail.users.settings.cse.identities.delete",
12692            http_method: hyper::Method::DELETE,
12693        });
12694
12695        for &field in ["userId", "cseEmailAddress"].iter() {
12696            if self._additional_params.contains_key(field) {
12697                dlg.finished(false);
12698                return Err(common::Error::FieldClash(field));
12699            }
12700        }
12701
12702        let mut params = Params::with_capacity(3 + self._additional_params.len());
12703        params.push("userId", self._user_id);
12704        params.push("cseEmailAddress", self._cse_email_address);
12705
12706        params.extend(self._additional_params.iter());
12707
12708        let mut url = self.hub._base_url.clone()
12709            + "gmail/v1/users/{userId}/settings/cse/identities/{cseEmailAddress}";
12710        if self._scopes.is_empty() {
12711            self._scopes
12712                .insert(Scope::SettingBasic.as_ref().to_string());
12713        }
12714
12715        #[allow(clippy::single_element_loop)]
12716        for &(find_this, param_name) in [
12717            ("{userId}", "userId"),
12718            ("{cseEmailAddress}", "cseEmailAddress"),
12719        ]
12720        .iter()
12721        {
12722            url = params.uri_replacement(url, param_name, find_this, false);
12723        }
12724        {
12725            let to_remove = ["cseEmailAddress", "userId"];
12726            params.remove_params(&to_remove);
12727        }
12728
12729        let url = params.parse_with_url(&url);
12730
12731        loop {
12732            let token = match self
12733                .hub
12734                .auth
12735                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
12736                .await
12737            {
12738                Ok(token) => token,
12739                Err(e) => match dlg.token(e) {
12740                    Ok(token) => token,
12741                    Err(e) => {
12742                        dlg.finished(false);
12743                        return Err(common::Error::MissingToken(e));
12744                    }
12745                },
12746            };
12747            let mut req_result = {
12748                let client = &self.hub.client;
12749                dlg.pre_request();
12750                let mut req_builder = hyper::Request::builder()
12751                    .method(hyper::Method::DELETE)
12752                    .uri(url.as_str())
12753                    .header(USER_AGENT, self.hub._user_agent.clone());
12754
12755                if let Some(token) = token.as_ref() {
12756                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
12757                }
12758
12759                let request = req_builder
12760                    .header(CONTENT_LENGTH, 0_u64)
12761                    .body(common::to_body::<String>(None));
12762
12763                client.request(request.unwrap()).await
12764            };
12765
12766            match req_result {
12767                Err(err) => {
12768                    if let common::Retry::After(d) = dlg.http_error(&err) {
12769                        sleep(d).await;
12770                        continue;
12771                    }
12772                    dlg.finished(false);
12773                    return Err(common::Error::HttpError(err));
12774                }
12775                Ok(res) => {
12776                    let (mut parts, body) = res.into_parts();
12777                    let mut body = common::Body::new(body);
12778                    if !parts.status.is_success() {
12779                        let bytes = common::to_bytes(body).await.unwrap_or_default();
12780                        let error = serde_json::from_str(&common::to_string(&bytes));
12781                        let response = common::to_response(parts, bytes.into());
12782
12783                        if let common::Retry::After(d) =
12784                            dlg.http_failure(&response, error.as_ref().ok())
12785                        {
12786                            sleep(d).await;
12787                            continue;
12788                        }
12789
12790                        dlg.finished(false);
12791
12792                        return Err(match error {
12793                            Ok(value) => common::Error::BadRequest(value),
12794                            _ => common::Error::Failure(response),
12795                        });
12796                    }
12797                    let response = common::Response::from_parts(parts, body);
12798
12799                    dlg.finished(true);
12800                    return Ok(response);
12801                }
12802            }
12803        }
12804    }
12805
12806    /// The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
12807    ///
12808    /// Sets the *user id* path property to the given value.
12809    ///
12810    /// Even though the property as already been set when instantiating this call,
12811    /// we provide this method for API completeness.
12812    pub fn user_id(mut self, new_value: &str) -> UserSettingCseIdentityDeleteCall<'a, C> {
12813        self._user_id = new_value.to_string();
12814        self
12815    }
12816    /// The primary email address associated with the client-side encryption identity configuration that's removed.
12817    ///
12818    /// Sets the *cse email address* path property to the given value.
12819    ///
12820    /// Even though the property as already been set when instantiating this call,
12821    /// we provide this method for API completeness.
12822    pub fn cse_email_address(mut self, new_value: &str) -> UserSettingCseIdentityDeleteCall<'a, C> {
12823        self._cse_email_address = new_value.to_string();
12824        self
12825    }
12826    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
12827    /// while executing the actual API request.
12828    ///
12829    /// ````text
12830    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
12831    /// ````
12832    ///
12833    /// Sets the *delegate* property to the given value.
12834    pub fn delegate(
12835        mut self,
12836        new_value: &'a mut dyn common::Delegate,
12837    ) -> UserSettingCseIdentityDeleteCall<'a, C> {
12838        self._delegate = Some(new_value);
12839        self
12840    }
12841
12842    /// Set any additional parameter of the query string used in the request.
12843    /// It should be used to set parameters which are not yet available through their own
12844    /// setters.
12845    ///
12846    /// Please note that this method must not be used to set any of the known parameters
12847    /// which have their own setter method. If done anyway, the request will fail.
12848    ///
12849    /// # Additional Parameters
12850    ///
12851    /// * *$.xgafv* (query-string) - V1 error format.
12852    /// * *access_token* (query-string) - OAuth access token.
12853    /// * *alt* (query-string) - Data format for response.
12854    /// * *callback* (query-string) - JSONP
12855    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
12856    /// * *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.
12857    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
12858    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
12859    /// * *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.
12860    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
12861    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
12862    pub fn param<T>(mut self, name: T, value: T) -> UserSettingCseIdentityDeleteCall<'a, C>
12863    where
12864        T: AsRef<str>,
12865    {
12866        self._additional_params
12867            .insert(name.as_ref().to_string(), value.as_ref().to_string());
12868        self
12869    }
12870
12871    /// Identifies the authorization scope for the method you are building.
12872    ///
12873    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
12874    /// [`Scope::SettingBasic`].
12875    ///
12876    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
12877    /// tokens for more than one scope.
12878    ///
12879    /// Usually there is more than one suitable scope to authorize an operation, some of which may
12880    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
12881    /// sufficient, a read-write scope will do as well.
12882    pub fn add_scope<St>(mut self, scope: St) -> UserSettingCseIdentityDeleteCall<'a, C>
12883    where
12884        St: AsRef<str>,
12885    {
12886        self._scopes.insert(String::from(scope.as_ref()));
12887        self
12888    }
12889    /// Identifies the authorization scope(s) for the method you are building.
12890    ///
12891    /// See [`Self::add_scope()`] for details.
12892    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingCseIdentityDeleteCall<'a, C>
12893    where
12894        I: IntoIterator<Item = St>,
12895        St: AsRef<str>,
12896    {
12897        self._scopes
12898            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
12899        self
12900    }
12901
12902    /// Removes all scopes, and no default scope will be used either.
12903    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
12904    /// for details).
12905    pub fn clear_scopes(mut self) -> UserSettingCseIdentityDeleteCall<'a, C> {
12906        self._scopes.clear();
12907        self
12908    }
12909}
12910
12911/// Retrieves a client-side encryption identity configuration.
12912///
12913/// A builder for the *settings.cse.identities.get* method supported by a *user* resource.
12914/// It is not used directly, but through a [`UserMethods`] instance.
12915///
12916/// # Example
12917///
12918/// Instantiate a resource method builder
12919///
12920/// ```test_harness,no_run
12921/// # extern crate hyper;
12922/// # extern crate hyper_rustls;
12923/// # extern crate google_gmail1 as gmail1;
12924/// # async fn dox() {
12925/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
12926///
12927/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
12928/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
12929/// #     secret,
12930/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
12931/// # ).build().await.unwrap();
12932///
12933/// # let client = hyper_util::client::legacy::Client::builder(
12934/// #     hyper_util::rt::TokioExecutor::new()
12935/// # )
12936/// # .build(
12937/// #     hyper_rustls::HttpsConnectorBuilder::new()
12938/// #         .with_native_roots()
12939/// #         .unwrap()
12940/// #         .https_or_http()
12941/// #         .enable_http1()
12942/// #         .build()
12943/// # );
12944/// # let mut hub = Gmail::new(client, auth);
12945/// // You can configure optional parameters by calling the respective setters at will, and
12946/// // execute the final call using `doit()`.
12947/// // Values shown here are possibly random and not representative !
12948/// let result = hub.users().settings_cse_identities_get("userId", "cseEmailAddress")
12949///              .doit().await;
12950/// # }
12951/// ```
12952pub struct UserSettingCseIdentityGetCall<'a, C>
12953where
12954    C: 'a,
12955{
12956    hub: &'a Gmail<C>,
12957    _user_id: String,
12958    _cse_email_address: String,
12959    _delegate: Option<&'a mut dyn common::Delegate>,
12960    _additional_params: HashMap<String, String>,
12961    _scopes: BTreeSet<String>,
12962}
12963
12964impl<'a, C> common::CallBuilder for UserSettingCseIdentityGetCall<'a, C> {}
12965
12966impl<'a, C> UserSettingCseIdentityGetCall<'a, C>
12967where
12968    C: common::Connector,
12969{
12970    /// Perform the operation you have build so far.
12971    pub async fn doit(mut self) -> common::Result<(common::Response, CseIdentity)> {
12972        use std::borrow::Cow;
12973        use std::io::{Read, Seek};
12974
12975        use common::{url::Params, ToParts};
12976        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
12977
12978        let mut dd = common::DefaultDelegate;
12979        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
12980        dlg.begin(common::MethodInfo {
12981            id: "gmail.users.settings.cse.identities.get",
12982            http_method: hyper::Method::GET,
12983        });
12984
12985        for &field in ["alt", "userId", "cseEmailAddress"].iter() {
12986            if self._additional_params.contains_key(field) {
12987                dlg.finished(false);
12988                return Err(common::Error::FieldClash(field));
12989            }
12990        }
12991
12992        let mut params = Params::with_capacity(4 + self._additional_params.len());
12993        params.push("userId", self._user_id);
12994        params.push("cseEmailAddress", self._cse_email_address);
12995
12996        params.extend(self._additional_params.iter());
12997
12998        params.push("alt", "json");
12999        let mut url = self.hub._base_url.clone()
13000            + "gmail/v1/users/{userId}/settings/cse/identities/{cseEmailAddress}";
13001        if self._scopes.is_empty() {
13002            self._scopes.insert(Scope::Readonly.as_ref().to_string());
13003        }
13004
13005        #[allow(clippy::single_element_loop)]
13006        for &(find_this, param_name) in [
13007            ("{userId}", "userId"),
13008            ("{cseEmailAddress}", "cseEmailAddress"),
13009        ]
13010        .iter()
13011        {
13012            url = params.uri_replacement(url, param_name, find_this, false);
13013        }
13014        {
13015            let to_remove = ["cseEmailAddress", "userId"];
13016            params.remove_params(&to_remove);
13017        }
13018
13019        let url = params.parse_with_url(&url);
13020
13021        loop {
13022            let token = match self
13023                .hub
13024                .auth
13025                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
13026                .await
13027            {
13028                Ok(token) => token,
13029                Err(e) => match dlg.token(e) {
13030                    Ok(token) => token,
13031                    Err(e) => {
13032                        dlg.finished(false);
13033                        return Err(common::Error::MissingToken(e));
13034                    }
13035                },
13036            };
13037            let mut req_result = {
13038                let client = &self.hub.client;
13039                dlg.pre_request();
13040                let mut req_builder = hyper::Request::builder()
13041                    .method(hyper::Method::GET)
13042                    .uri(url.as_str())
13043                    .header(USER_AGENT, self.hub._user_agent.clone());
13044
13045                if let Some(token) = token.as_ref() {
13046                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
13047                }
13048
13049                let request = req_builder
13050                    .header(CONTENT_LENGTH, 0_u64)
13051                    .body(common::to_body::<String>(None));
13052
13053                client.request(request.unwrap()).await
13054            };
13055
13056            match req_result {
13057                Err(err) => {
13058                    if let common::Retry::After(d) = dlg.http_error(&err) {
13059                        sleep(d).await;
13060                        continue;
13061                    }
13062                    dlg.finished(false);
13063                    return Err(common::Error::HttpError(err));
13064                }
13065                Ok(res) => {
13066                    let (mut parts, body) = res.into_parts();
13067                    let mut body = common::Body::new(body);
13068                    if !parts.status.is_success() {
13069                        let bytes = common::to_bytes(body).await.unwrap_or_default();
13070                        let error = serde_json::from_str(&common::to_string(&bytes));
13071                        let response = common::to_response(parts, bytes.into());
13072
13073                        if let common::Retry::After(d) =
13074                            dlg.http_failure(&response, error.as_ref().ok())
13075                        {
13076                            sleep(d).await;
13077                            continue;
13078                        }
13079
13080                        dlg.finished(false);
13081
13082                        return Err(match error {
13083                            Ok(value) => common::Error::BadRequest(value),
13084                            _ => common::Error::Failure(response),
13085                        });
13086                    }
13087                    let response = {
13088                        let bytes = common::to_bytes(body).await.unwrap_or_default();
13089                        let encoded = common::to_string(&bytes);
13090                        match serde_json::from_str(&encoded) {
13091                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
13092                            Err(error) => {
13093                                dlg.response_json_decode_error(&encoded, &error);
13094                                return Err(common::Error::JsonDecodeError(
13095                                    encoded.to_string(),
13096                                    error,
13097                                ));
13098                            }
13099                        }
13100                    };
13101
13102                    dlg.finished(true);
13103                    return Ok(response);
13104                }
13105            }
13106        }
13107    }
13108
13109    /// The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
13110    ///
13111    /// Sets the *user id* path property to the given value.
13112    ///
13113    /// Even though the property as already been set when instantiating this call,
13114    /// we provide this method for API completeness.
13115    pub fn user_id(mut self, new_value: &str) -> UserSettingCseIdentityGetCall<'a, C> {
13116        self._user_id = new_value.to_string();
13117        self
13118    }
13119    /// The primary email address associated with the client-side encryption identity configuration that's retrieved.
13120    ///
13121    /// Sets the *cse email address* path property to the given value.
13122    ///
13123    /// Even though the property as already been set when instantiating this call,
13124    /// we provide this method for API completeness.
13125    pub fn cse_email_address(mut self, new_value: &str) -> UserSettingCseIdentityGetCall<'a, C> {
13126        self._cse_email_address = new_value.to_string();
13127        self
13128    }
13129    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
13130    /// while executing the actual API request.
13131    ///
13132    /// ````text
13133    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
13134    /// ````
13135    ///
13136    /// Sets the *delegate* property to the given value.
13137    pub fn delegate(
13138        mut self,
13139        new_value: &'a mut dyn common::Delegate,
13140    ) -> UserSettingCseIdentityGetCall<'a, C> {
13141        self._delegate = Some(new_value);
13142        self
13143    }
13144
13145    /// Set any additional parameter of the query string used in the request.
13146    /// It should be used to set parameters which are not yet available through their own
13147    /// setters.
13148    ///
13149    /// Please note that this method must not be used to set any of the known parameters
13150    /// which have their own setter method. If done anyway, the request will fail.
13151    ///
13152    /// # Additional Parameters
13153    ///
13154    /// * *$.xgafv* (query-string) - V1 error format.
13155    /// * *access_token* (query-string) - OAuth access token.
13156    /// * *alt* (query-string) - Data format for response.
13157    /// * *callback* (query-string) - JSONP
13158    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
13159    /// * *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.
13160    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
13161    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
13162    /// * *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.
13163    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
13164    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
13165    pub fn param<T>(mut self, name: T, value: T) -> UserSettingCseIdentityGetCall<'a, C>
13166    where
13167        T: AsRef<str>,
13168    {
13169        self._additional_params
13170            .insert(name.as_ref().to_string(), value.as_ref().to_string());
13171        self
13172    }
13173
13174    /// Identifies the authorization scope for the method you are building.
13175    ///
13176    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
13177    /// [`Scope::Readonly`].
13178    ///
13179    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
13180    /// tokens for more than one scope.
13181    ///
13182    /// Usually there is more than one suitable scope to authorize an operation, some of which may
13183    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
13184    /// sufficient, a read-write scope will do as well.
13185    pub fn add_scope<St>(mut self, scope: St) -> UserSettingCseIdentityGetCall<'a, C>
13186    where
13187        St: AsRef<str>,
13188    {
13189        self._scopes.insert(String::from(scope.as_ref()));
13190        self
13191    }
13192    /// Identifies the authorization scope(s) for the method you are building.
13193    ///
13194    /// See [`Self::add_scope()`] for details.
13195    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingCseIdentityGetCall<'a, C>
13196    where
13197        I: IntoIterator<Item = St>,
13198        St: AsRef<str>,
13199    {
13200        self._scopes
13201            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
13202        self
13203    }
13204
13205    /// Removes all scopes, and no default scope will be used either.
13206    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
13207    /// for details).
13208    pub fn clear_scopes(mut self) -> UserSettingCseIdentityGetCall<'a, C> {
13209        self._scopes.clear();
13210        self
13211    }
13212}
13213
13214/// Lists the client-side encrypted identities for an authenticated user.
13215///
13216/// A builder for the *settings.cse.identities.list* method supported by a *user* resource.
13217/// It is not used directly, but through a [`UserMethods`] instance.
13218///
13219/// # Example
13220///
13221/// Instantiate a resource method builder
13222///
13223/// ```test_harness,no_run
13224/// # extern crate hyper;
13225/// # extern crate hyper_rustls;
13226/// # extern crate google_gmail1 as gmail1;
13227/// # async fn dox() {
13228/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
13229///
13230/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
13231/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
13232/// #     secret,
13233/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
13234/// # ).build().await.unwrap();
13235///
13236/// # let client = hyper_util::client::legacy::Client::builder(
13237/// #     hyper_util::rt::TokioExecutor::new()
13238/// # )
13239/// # .build(
13240/// #     hyper_rustls::HttpsConnectorBuilder::new()
13241/// #         .with_native_roots()
13242/// #         .unwrap()
13243/// #         .https_or_http()
13244/// #         .enable_http1()
13245/// #         .build()
13246/// # );
13247/// # let mut hub = Gmail::new(client, auth);
13248/// // You can configure optional parameters by calling the respective setters at will, and
13249/// // execute the final call using `doit()`.
13250/// // Values shown here are possibly random and not representative !
13251/// let result = hub.users().settings_cse_identities_list("userId")
13252///              .page_token("voluptua.")
13253///              .page_size(-2)
13254///              .doit().await;
13255/// # }
13256/// ```
13257pub struct UserSettingCseIdentityListCall<'a, C>
13258where
13259    C: 'a,
13260{
13261    hub: &'a Gmail<C>,
13262    _user_id: String,
13263    _page_token: Option<String>,
13264    _page_size: Option<i32>,
13265    _delegate: Option<&'a mut dyn common::Delegate>,
13266    _additional_params: HashMap<String, String>,
13267    _scopes: BTreeSet<String>,
13268}
13269
13270impl<'a, C> common::CallBuilder for UserSettingCseIdentityListCall<'a, C> {}
13271
13272impl<'a, C> UserSettingCseIdentityListCall<'a, C>
13273where
13274    C: common::Connector,
13275{
13276    /// Perform the operation you have build so far.
13277    pub async fn doit(mut self) -> common::Result<(common::Response, ListCseIdentitiesResponse)> {
13278        use std::borrow::Cow;
13279        use std::io::{Read, Seek};
13280
13281        use common::{url::Params, ToParts};
13282        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
13283
13284        let mut dd = common::DefaultDelegate;
13285        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
13286        dlg.begin(common::MethodInfo {
13287            id: "gmail.users.settings.cse.identities.list",
13288            http_method: hyper::Method::GET,
13289        });
13290
13291        for &field in ["alt", "userId", "pageToken", "pageSize"].iter() {
13292            if self._additional_params.contains_key(field) {
13293                dlg.finished(false);
13294                return Err(common::Error::FieldClash(field));
13295            }
13296        }
13297
13298        let mut params = Params::with_capacity(5 + self._additional_params.len());
13299        params.push("userId", self._user_id);
13300        if let Some(value) = self._page_token.as_ref() {
13301            params.push("pageToken", value);
13302        }
13303        if let Some(value) = self._page_size.as_ref() {
13304            params.push("pageSize", value.to_string());
13305        }
13306
13307        params.extend(self._additional_params.iter());
13308
13309        params.push("alt", "json");
13310        let mut url =
13311            self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/cse/identities";
13312        if self._scopes.is_empty() {
13313            self._scopes.insert(Scope::Readonly.as_ref().to_string());
13314        }
13315
13316        #[allow(clippy::single_element_loop)]
13317        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
13318            url = params.uri_replacement(url, param_name, find_this, false);
13319        }
13320        {
13321            let to_remove = ["userId"];
13322            params.remove_params(&to_remove);
13323        }
13324
13325        let url = params.parse_with_url(&url);
13326
13327        loop {
13328            let token = match self
13329                .hub
13330                .auth
13331                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
13332                .await
13333            {
13334                Ok(token) => token,
13335                Err(e) => match dlg.token(e) {
13336                    Ok(token) => token,
13337                    Err(e) => {
13338                        dlg.finished(false);
13339                        return Err(common::Error::MissingToken(e));
13340                    }
13341                },
13342            };
13343            let mut req_result = {
13344                let client = &self.hub.client;
13345                dlg.pre_request();
13346                let mut req_builder = hyper::Request::builder()
13347                    .method(hyper::Method::GET)
13348                    .uri(url.as_str())
13349                    .header(USER_AGENT, self.hub._user_agent.clone());
13350
13351                if let Some(token) = token.as_ref() {
13352                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
13353                }
13354
13355                let request = req_builder
13356                    .header(CONTENT_LENGTH, 0_u64)
13357                    .body(common::to_body::<String>(None));
13358
13359                client.request(request.unwrap()).await
13360            };
13361
13362            match req_result {
13363                Err(err) => {
13364                    if let common::Retry::After(d) = dlg.http_error(&err) {
13365                        sleep(d).await;
13366                        continue;
13367                    }
13368                    dlg.finished(false);
13369                    return Err(common::Error::HttpError(err));
13370                }
13371                Ok(res) => {
13372                    let (mut parts, body) = res.into_parts();
13373                    let mut body = common::Body::new(body);
13374                    if !parts.status.is_success() {
13375                        let bytes = common::to_bytes(body).await.unwrap_or_default();
13376                        let error = serde_json::from_str(&common::to_string(&bytes));
13377                        let response = common::to_response(parts, bytes.into());
13378
13379                        if let common::Retry::After(d) =
13380                            dlg.http_failure(&response, error.as_ref().ok())
13381                        {
13382                            sleep(d).await;
13383                            continue;
13384                        }
13385
13386                        dlg.finished(false);
13387
13388                        return Err(match error {
13389                            Ok(value) => common::Error::BadRequest(value),
13390                            _ => common::Error::Failure(response),
13391                        });
13392                    }
13393                    let response = {
13394                        let bytes = common::to_bytes(body).await.unwrap_or_default();
13395                        let encoded = common::to_string(&bytes);
13396                        match serde_json::from_str(&encoded) {
13397                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
13398                            Err(error) => {
13399                                dlg.response_json_decode_error(&encoded, &error);
13400                                return Err(common::Error::JsonDecodeError(
13401                                    encoded.to_string(),
13402                                    error,
13403                                ));
13404                            }
13405                        }
13406                    };
13407
13408                    dlg.finished(true);
13409                    return Ok(response);
13410                }
13411            }
13412        }
13413    }
13414
13415    /// The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
13416    ///
13417    /// Sets the *user id* path property to the given value.
13418    ///
13419    /// Even though the property as already been set when instantiating this call,
13420    /// we provide this method for API completeness.
13421    pub fn user_id(mut self, new_value: &str) -> UserSettingCseIdentityListCall<'a, C> {
13422        self._user_id = new_value.to_string();
13423        self
13424    }
13425    /// Pagination token indicating which page of identities to return. If the token is not supplied, then the API will return the first page of results.
13426    ///
13427    /// Sets the *page token* query property to the given value.
13428    pub fn page_token(mut self, new_value: &str) -> UserSettingCseIdentityListCall<'a, C> {
13429        self._page_token = Some(new_value.to_string());
13430        self
13431    }
13432    /// The number of identities to return. If not provided, the page size will default to 20 entries.
13433    ///
13434    /// Sets the *page size* query property to the given value.
13435    pub fn page_size(mut self, new_value: i32) -> UserSettingCseIdentityListCall<'a, C> {
13436        self._page_size = Some(new_value);
13437        self
13438    }
13439    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
13440    /// while executing the actual API request.
13441    ///
13442    /// ````text
13443    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
13444    /// ````
13445    ///
13446    /// Sets the *delegate* property to the given value.
13447    pub fn delegate(
13448        mut self,
13449        new_value: &'a mut dyn common::Delegate,
13450    ) -> UserSettingCseIdentityListCall<'a, C> {
13451        self._delegate = Some(new_value);
13452        self
13453    }
13454
13455    /// Set any additional parameter of the query string used in the request.
13456    /// It should be used to set parameters which are not yet available through their own
13457    /// setters.
13458    ///
13459    /// Please note that this method must not be used to set any of the known parameters
13460    /// which have their own setter method. If done anyway, the request will fail.
13461    ///
13462    /// # Additional Parameters
13463    ///
13464    /// * *$.xgafv* (query-string) - V1 error format.
13465    /// * *access_token* (query-string) - OAuth access token.
13466    /// * *alt* (query-string) - Data format for response.
13467    /// * *callback* (query-string) - JSONP
13468    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
13469    /// * *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.
13470    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
13471    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
13472    /// * *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.
13473    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
13474    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
13475    pub fn param<T>(mut self, name: T, value: T) -> UserSettingCseIdentityListCall<'a, C>
13476    where
13477        T: AsRef<str>,
13478    {
13479        self._additional_params
13480            .insert(name.as_ref().to_string(), value.as_ref().to_string());
13481        self
13482    }
13483
13484    /// Identifies the authorization scope for the method you are building.
13485    ///
13486    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
13487    /// [`Scope::Readonly`].
13488    ///
13489    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
13490    /// tokens for more than one scope.
13491    ///
13492    /// Usually there is more than one suitable scope to authorize an operation, some of which may
13493    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
13494    /// sufficient, a read-write scope will do as well.
13495    pub fn add_scope<St>(mut self, scope: St) -> UserSettingCseIdentityListCall<'a, C>
13496    where
13497        St: AsRef<str>,
13498    {
13499        self._scopes.insert(String::from(scope.as_ref()));
13500        self
13501    }
13502    /// Identifies the authorization scope(s) for the method you are building.
13503    ///
13504    /// See [`Self::add_scope()`] for details.
13505    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingCseIdentityListCall<'a, C>
13506    where
13507        I: IntoIterator<Item = St>,
13508        St: AsRef<str>,
13509    {
13510        self._scopes
13511            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
13512        self
13513    }
13514
13515    /// Removes all scopes, and no default scope will be used either.
13516    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
13517    /// for details).
13518    pub fn clear_scopes(mut self) -> UserSettingCseIdentityListCall<'a, C> {
13519        self._scopes.clear();
13520        self
13521    }
13522}
13523
13524/// Associates a different key pair with an existing client-side encryption identity. The updated key pair must validate against Google's [S/MIME certificate profiles](https://support.google.com/a/answer/7300887).
13525///
13526/// A builder for the *settings.cse.identities.patch* method supported by a *user* resource.
13527/// It is not used directly, but through a [`UserMethods`] instance.
13528///
13529/// # Example
13530///
13531/// Instantiate a resource method builder
13532///
13533/// ```test_harness,no_run
13534/// # extern crate hyper;
13535/// # extern crate hyper_rustls;
13536/// # extern crate google_gmail1 as gmail1;
13537/// use gmail1::api::CseIdentity;
13538/// # async fn dox() {
13539/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
13540///
13541/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
13542/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
13543/// #     secret,
13544/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
13545/// # ).build().await.unwrap();
13546///
13547/// # let client = hyper_util::client::legacy::Client::builder(
13548/// #     hyper_util::rt::TokioExecutor::new()
13549/// # )
13550/// # .build(
13551/// #     hyper_rustls::HttpsConnectorBuilder::new()
13552/// #         .with_native_roots()
13553/// #         .unwrap()
13554/// #         .https_or_http()
13555/// #         .enable_http1()
13556/// #         .build()
13557/// # );
13558/// # let mut hub = Gmail::new(client, auth);
13559/// // As the method needs a request, you would usually fill it with the desired information
13560/// // into the respective structure. Some of the parts shown here might not be applicable !
13561/// // Values shown here are possibly random and not representative !
13562/// let mut req = CseIdentity::default();
13563///
13564/// // You can configure optional parameters by calling the respective setters at will, and
13565/// // execute the final call using `doit()`.
13566/// // Values shown here are possibly random and not representative !
13567/// let result = hub.users().settings_cse_identities_patch(req, "userId", "emailAddress")
13568///              .doit().await;
13569/// # }
13570/// ```
13571pub struct UserSettingCseIdentityPatchCall<'a, C>
13572where
13573    C: 'a,
13574{
13575    hub: &'a Gmail<C>,
13576    _request: CseIdentity,
13577    _user_id: String,
13578    _email_address: String,
13579    _delegate: Option<&'a mut dyn common::Delegate>,
13580    _additional_params: HashMap<String, String>,
13581    _scopes: BTreeSet<String>,
13582}
13583
13584impl<'a, C> common::CallBuilder for UserSettingCseIdentityPatchCall<'a, C> {}
13585
13586impl<'a, C> UserSettingCseIdentityPatchCall<'a, C>
13587where
13588    C: common::Connector,
13589{
13590    /// Perform the operation you have build so far.
13591    pub async fn doit(mut self) -> common::Result<(common::Response, CseIdentity)> {
13592        use std::borrow::Cow;
13593        use std::io::{Read, Seek};
13594
13595        use common::{url::Params, ToParts};
13596        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
13597
13598        let mut dd = common::DefaultDelegate;
13599        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
13600        dlg.begin(common::MethodInfo {
13601            id: "gmail.users.settings.cse.identities.patch",
13602            http_method: hyper::Method::PATCH,
13603        });
13604
13605        for &field in ["alt", "userId", "emailAddress"].iter() {
13606            if self._additional_params.contains_key(field) {
13607                dlg.finished(false);
13608                return Err(common::Error::FieldClash(field));
13609            }
13610        }
13611
13612        let mut params = Params::with_capacity(5 + self._additional_params.len());
13613        params.push("userId", self._user_id);
13614        params.push("emailAddress", self._email_address);
13615
13616        params.extend(self._additional_params.iter());
13617
13618        params.push("alt", "json");
13619        let mut url = self.hub._base_url.clone()
13620            + "gmail/v1/users/{userId}/settings/cse/identities/{emailAddress}";
13621        if self._scopes.is_empty() {
13622            self._scopes
13623                .insert(Scope::SettingBasic.as_ref().to_string());
13624        }
13625
13626        #[allow(clippy::single_element_loop)]
13627        for &(find_this, param_name) in
13628            [("{userId}", "userId"), ("{emailAddress}", "emailAddress")].iter()
13629        {
13630            url = params.uri_replacement(url, param_name, find_this, false);
13631        }
13632        {
13633            let to_remove = ["emailAddress", "userId"];
13634            params.remove_params(&to_remove);
13635        }
13636
13637        let url = params.parse_with_url(&url);
13638
13639        let mut json_mime_type = mime::APPLICATION_JSON;
13640        let mut request_value_reader = {
13641            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
13642            common::remove_json_null_values(&mut value);
13643            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
13644            serde_json::to_writer(&mut dst, &value).unwrap();
13645            dst
13646        };
13647        let request_size = request_value_reader
13648            .seek(std::io::SeekFrom::End(0))
13649            .unwrap();
13650        request_value_reader
13651            .seek(std::io::SeekFrom::Start(0))
13652            .unwrap();
13653
13654        loop {
13655            let token = match self
13656                .hub
13657                .auth
13658                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
13659                .await
13660            {
13661                Ok(token) => token,
13662                Err(e) => match dlg.token(e) {
13663                    Ok(token) => token,
13664                    Err(e) => {
13665                        dlg.finished(false);
13666                        return Err(common::Error::MissingToken(e));
13667                    }
13668                },
13669            };
13670            request_value_reader
13671                .seek(std::io::SeekFrom::Start(0))
13672                .unwrap();
13673            let mut req_result = {
13674                let client = &self.hub.client;
13675                dlg.pre_request();
13676                let mut req_builder = hyper::Request::builder()
13677                    .method(hyper::Method::PATCH)
13678                    .uri(url.as_str())
13679                    .header(USER_AGENT, self.hub._user_agent.clone());
13680
13681                if let Some(token) = token.as_ref() {
13682                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
13683                }
13684
13685                let request = req_builder
13686                    .header(CONTENT_TYPE, json_mime_type.to_string())
13687                    .header(CONTENT_LENGTH, request_size as u64)
13688                    .body(common::to_body(
13689                        request_value_reader.get_ref().clone().into(),
13690                    ));
13691
13692                client.request(request.unwrap()).await
13693            };
13694
13695            match req_result {
13696                Err(err) => {
13697                    if let common::Retry::After(d) = dlg.http_error(&err) {
13698                        sleep(d).await;
13699                        continue;
13700                    }
13701                    dlg.finished(false);
13702                    return Err(common::Error::HttpError(err));
13703                }
13704                Ok(res) => {
13705                    let (mut parts, body) = res.into_parts();
13706                    let mut body = common::Body::new(body);
13707                    if !parts.status.is_success() {
13708                        let bytes = common::to_bytes(body).await.unwrap_or_default();
13709                        let error = serde_json::from_str(&common::to_string(&bytes));
13710                        let response = common::to_response(parts, bytes.into());
13711
13712                        if let common::Retry::After(d) =
13713                            dlg.http_failure(&response, error.as_ref().ok())
13714                        {
13715                            sleep(d).await;
13716                            continue;
13717                        }
13718
13719                        dlg.finished(false);
13720
13721                        return Err(match error {
13722                            Ok(value) => common::Error::BadRequest(value),
13723                            _ => common::Error::Failure(response),
13724                        });
13725                    }
13726                    let response = {
13727                        let bytes = common::to_bytes(body).await.unwrap_or_default();
13728                        let encoded = common::to_string(&bytes);
13729                        match serde_json::from_str(&encoded) {
13730                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
13731                            Err(error) => {
13732                                dlg.response_json_decode_error(&encoded, &error);
13733                                return Err(common::Error::JsonDecodeError(
13734                                    encoded.to_string(),
13735                                    error,
13736                                ));
13737                            }
13738                        }
13739                    };
13740
13741                    dlg.finished(true);
13742                    return Ok(response);
13743                }
13744            }
13745        }
13746    }
13747
13748    ///
13749    /// Sets the *request* property to the given value.
13750    ///
13751    /// Even though the property as already been set when instantiating this call,
13752    /// we provide this method for API completeness.
13753    pub fn request(mut self, new_value: CseIdentity) -> UserSettingCseIdentityPatchCall<'a, C> {
13754        self._request = new_value;
13755        self
13756    }
13757    /// The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
13758    ///
13759    /// Sets the *user id* path property to the given value.
13760    ///
13761    /// Even though the property as already been set when instantiating this call,
13762    /// we provide this method for API completeness.
13763    pub fn user_id(mut self, new_value: &str) -> UserSettingCseIdentityPatchCall<'a, C> {
13764        self._user_id = new_value.to_string();
13765        self
13766    }
13767    /// The email address of the client-side encryption identity to update.
13768    ///
13769    /// Sets the *email address* path property to the given value.
13770    ///
13771    /// Even though the property as already been set when instantiating this call,
13772    /// we provide this method for API completeness.
13773    pub fn email_address(mut self, new_value: &str) -> UserSettingCseIdentityPatchCall<'a, C> {
13774        self._email_address = new_value.to_string();
13775        self
13776    }
13777    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
13778    /// while executing the actual API request.
13779    ///
13780    /// ````text
13781    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
13782    /// ````
13783    ///
13784    /// Sets the *delegate* property to the given value.
13785    pub fn delegate(
13786        mut self,
13787        new_value: &'a mut dyn common::Delegate,
13788    ) -> UserSettingCseIdentityPatchCall<'a, C> {
13789        self._delegate = Some(new_value);
13790        self
13791    }
13792
13793    /// Set any additional parameter of the query string used in the request.
13794    /// It should be used to set parameters which are not yet available through their own
13795    /// setters.
13796    ///
13797    /// Please note that this method must not be used to set any of the known parameters
13798    /// which have their own setter method. If done anyway, the request will fail.
13799    ///
13800    /// # Additional Parameters
13801    ///
13802    /// * *$.xgafv* (query-string) - V1 error format.
13803    /// * *access_token* (query-string) - OAuth access token.
13804    /// * *alt* (query-string) - Data format for response.
13805    /// * *callback* (query-string) - JSONP
13806    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
13807    /// * *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.
13808    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
13809    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
13810    /// * *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.
13811    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
13812    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
13813    pub fn param<T>(mut self, name: T, value: T) -> UserSettingCseIdentityPatchCall<'a, C>
13814    where
13815        T: AsRef<str>,
13816    {
13817        self._additional_params
13818            .insert(name.as_ref().to_string(), value.as_ref().to_string());
13819        self
13820    }
13821
13822    /// Identifies the authorization scope for the method you are building.
13823    ///
13824    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
13825    /// [`Scope::SettingBasic`].
13826    ///
13827    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
13828    /// tokens for more than one scope.
13829    ///
13830    /// Usually there is more than one suitable scope to authorize an operation, some of which may
13831    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
13832    /// sufficient, a read-write scope will do as well.
13833    pub fn add_scope<St>(mut self, scope: St) -> UserSettingCseIdentityPatchCall<'a, C>
13834    where
13835        St: AsRef<str>,
13836    {
13837        self._scopes.insert(String::from(scope.as_ref()));
13838        self
13839    }
13840    /// Identifies the authorization scope(s) for the method you are building.
13841    ///
13842    /// See [`Self::add_scope()`] for details.
13843    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingCseIdentityPatchCall<'a, C>
13844    where
13845        I: IntoIterator<Item = St>,
13846        St: AsRef<str>,
13847    {
13848        self._scopes
13849            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
13850        self
13851    }
13852
13853    /// Removes all scopes, and no default scope will be used either.
13854    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
13855    /// for details).
13856    pub fn clear_scopes(mut self) -> UserSettingCseIdentityPatchCall<'a, C> {
13857        self._scopes.clear();
13858        self
13859    }
13860}
13861
13862/// Creates and uploads a client-side encryption S/MIME public key certificate chain and private key metadata for the authenticated user.
13863///
13864/// A builder for the *settings.cse.keypairs.create* method supported by a *user* resource.
13865/// It is not used directly, but through a [`UserMethods`] instance.
13866///
13867/// # Example
13868///
13869/// Instantiate a resource method builder
13870///
13871/// ```test_harness,no_run
13872/// # extern crate hyper;
13873/// # extern crate hyper_rustls;
13874/// # extern crate google_gmail1 as gmail1;
13875/// use gmail1::api::CseKeyPair;
13876/// # async fn dox() {
13877/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
13878///
13879/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
13880/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
13881/// #     secret,
13882/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
13883/// # ).build().await.unwrap();
13884///
13885/// # let client = hyper_util::client::legacy::Client::builder(
13886/// #     hyper_util::rt::TokioExecutor::new()
13887/// # )
13888/// # .build(
13889/// #     hyper_rustls::HttpsConnectorBuilder::new()
13890/// #         .with_native_roots()
13891/// #         .unwrap()
13892/// #         .https_or_http()
13893/// #         .enable_http1()
13894/// #         .build()
13895/// # );
13896/// # let mut hub = Gmail::new(client, auth);
13897/// // As the method needs a request, you would usually fill it with the desired information
13898/// // into the respective structure. Some of the parts shown here might not be applicable !
13899/// // Values shown here are possibly random and not representative !
13900/// let mut req = CseKeyPair::default();
13901///
13902/// // You can configure optional parameters by calling the respective setters at will, and
13903/// // execute the final call using `doit()`.
13904/// // Values shown here are possibly random and not representative !
13905/// let result = hub.users().settings_cse_keypairs_create(req, "userId")
13906///              .doit().await;
13907/// # }
13908/// ```
13909pub struct UserSettingCseKeypairCreateCall<'a, C>
13910where
13911    C: 'a,
13912{
13913    hub: &'a Gmail<C>,
13914    _request: CseKeyPair,
13915    _user_id: String,
13916    _delegate: Option<&'a mut dyn common::Delegate>,
13917    _additional_params: HashMap<String, String>,
13918    _scopes: BTreeSet<String>,
13919}
13920
13921impl<'a, C> common::CallBuilder for UserSettingCseKeypairCreateCall<'a, C> {}
13922
13923impl<'a, C> UserSettingCseKeypairCreateCall<'a, C>
13924where
13925    C: common::Connector,
13926{
13927    /// Perform the operation you have build so far.
13928    pub async fn doit(mut self) -> common::Result<(common::Response, CseKeyPair)> {
13929        use std::borrow::Cow;
13930        use std::io::{Read, Seek};
13931
13932        use common::{url::Params, ToParts};
13933        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
13934
13935        let mut dd = common::DefaultDelegate;
13936        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
13937        dlg.begin(common::MethodInfo {
13938            id: "gmail.users.settings.cse.keypairs.create",
13939            http_method: hyper::Method::POST,
13940        });
13941
13942        for &field in ["alt", "userId"].iter() {
13943            if self._additional_params.contains_key(field) {
13944                dlg.finished(false);
13945                return Err(common::Error::FieldClash(field));
13946            }
13947        }
13948
13949        let mut params = Params::with_capacity(4 + self._additional_params.len());
13950        params.push("userId", self._user_id);
13951
13952        params.extend(self._additional_params.iter());
13953
13954        params.push("alt", "json");
13955        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/cse/keypairs";
13956        if self._scopes.is_empty() {
13957            self._scopes
13958                .insert(Scope::SettingBasic.as_ref().to_string());
13959        }
13960
13961        #[allow(clippy::single_element_loop)]
13962        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
13963            url = params.uri_replacement(url, param_name, find_this, false);
13964        }
13965        {
13966            let to_remove = ["userId"];
13967            params.remove_params(&to_remove);
13968        }
13969
13970        let url = params.parse_with_url(&url);
13971
13972        let mut json_mime_type = mime::APPLICATION_JSON;
13973        let mut request_value_reader = {
13974            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
13975            common::remove_json_null_values(&mut value);
13976            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
13977            serde_json::to_writer(&mut dst, &value).unwrap();
13978            dst
13979        };
13980        let request_size = request_value_reader
13981            .seek(std::io::SeekFrom::End(0))
13982            .unwrap();
13983        request_value_reader
13984            .seek(std::io::SeekFrom::Start(0))
13985            .unwrap();
13986
13987        loop {
13988            let token = match self
13989                .hub
13990                .auth
13991                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
13992                .await
13993            {
13994                Ok(token) => token,
13995                Err(e) => match dlg.token(e) {
13996                    Ok(token) => token,
13997                    Err(e) => {
13998                        dlg.finished(false);
13999                        return Err(common::Error::MissingToken(e));
14000                    }
14001                },
14002            };
14003            request_value_reader
14004                .seek(std::io::SeekFrom::Start(0))
14005                .unwrap();
14006            let mut req_result = {
14007                let client = &self.hub.client;
14008                dlg.pre_request();
14009                let mut req_builder = hyper::Request::builder()
14010                    .method(hyper::Method::POST)
14011                    .uri(url.as_str())
14012                    .header(USER_AGENT, self.hub._user_agent.clone());
14013
14014                if let Some(token) = token.as_ref() {
14015                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
14016                }
14017
14018                let request = req_builder
14019                    .header(CONTENT_TYPE, json_mime_type.to_string())
14020                    .header(CONTENT_LENGTH, request_size as u64)
14021                    .body(common::to_body(
14022                        request_value_reader.get_ref().clone().into(),
14023                    ));
14024
14025                client.request(request.unwrap()).await
14026            };
14027
14028            match req_result {
14029                Err(err) => {
14030                    if let common::Retry::After(d) = dlg.http_error(&err) {
14031                        sleep(d).await;
14032                        continue;
14033                    }
14034                    dlg.finished(false);
14035                    return Err(common::Error::HttpError(err));
14036                }
14037                Ok(res) => {
14038                    let (mut parts, body) = res.into_parts();
14039                    let mut body = common::Body::new(body);
14040                    if !parts.status.is_success() {
14041                        let bytes = common::to_bytes(body).await.unwrap_or_default();
14042                        let error = serde_json::from_str(&common::to_string(&bytes));
14043                        let response = common::to_response(parts, bytes.into());
14044
14045                        if let common::Retry::After(d) =
14046                            dlg.http_failure(&response, error.as_ref().ok())
14047                        {
14048                            sleep(d).await;
14049                            continue;
14050                        }
14051
14052                        dlg.finished(false);
14053
14054                        return Err(match error {
14055                            Ok(value) => common::Error::BadRequest(value),
14056                            _ => common::Error::Failure(response),
14057                        });
14058                    }
14059                    let response = {
14060                        let bytes = common::to_bytes(body).await.unwrap_or_default();
14061                        let encoded = common::to_string(&bytes);
14062                        match serde_json::from_str(&encoded) {
14063                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
14064                            Err(error) => {
14065                                dlg.response_json_decode_error(&encoded, &error);
14066                                return Err(common::Error::JsonDecodeError(
14067                                    encoded.to_string(),
14068                                    error,
14069                                ));
14070                            }
14071                        }
14072                    };
14073
14074                    dlg.finished(true);
14075                    return Ok(response);
14076                }
14077            }
14078        }
14079    }
14080
14081    ///
14082    /// Sets the *request* property to the given value.
14083    ///
14084    /// Even though the property as already been set when instantiating this call,
14085    /// we provide this method for API completeness.
14086    pub fn request(mut self, new_value: CseKeyPair) -> UserSettingCseKeypairCreateCall<'a, C> {
14087        self._request = new_value;
14088        self
14089    }
14090    /// The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
14091    ///
14092    /// Sets the *user id* path property to the given value.
14093    ///
14094    /// Even though the property as already been set when instantiating this call,
14095    /// we provide this method for API completeness.
14096    pub fn user_id(mut self, new_value: &str) -> UserSettingCseKeypairCreateCall<'a, C> {
14097        self._user_id = new_value.to_string();
14098        self
14099    }
14100    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
14101    /// while executing the actual API request.
14102    ///
14103    /// ````text
14104    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
14105    /// ````
14106    ///
14107    /// Sets the *delegate* property to the given value.
14108    pub fn delegate(
14109        mut self,
14110        new_value: &'a mut dyn common::Delegate,
14111    ) -> UserSettingCseKeypairCreateCall<'a, C> {
14112        self._delegate = Some(new_value);
14113        self
14114    }
14115
14116    /// Set any additional parameter of the query string used in the request.
14117    /// It should be used to set parameters which are not yet available through their own
14118    /// setters.
14119    ///
14120    /// Please note that this method must not be used to set any of the known parameters
14121    /// which have their own setter method. If done anyway, the request will fail.
14122    ///
14123    /// # Additional Parameters
14124    ///
14125    /// * *$.xgafv* (query-string) - V1 error format.
14126    /// * *access_token* (query-string) - OAuth access token.
14127    /// * *alt* (query-string) - Data format for response.
14128    /// * *callback* (query-string) - JSONP
14129    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
14130    /// * *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.
14131    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
14132    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
14133    /// * *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.
14134    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
14135    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
14136    pub fn param<T>(mut self, name: T, value: T) -> UserSettingCseKeypairCreateCall<'a, C>
14137    where
14138        T: AsRef<str>,
14139    {
14140        self._additional_params
14141            .insert(name.as_ref().to_string(), value.as_ref().to_string());
14142        self
14143    }
14144
14145    /// Identifies the authorization scope for the method you are building.
14146    ///
14147    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
14148    /// [`Scope::SettingBasic`].
14149    ///
14150    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
14151    /// tokens for more than one scope.
14152    ///
14153    /// Usually there is more than one suitable scope to authorize an operation, some of which may
14154    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
14155    /// sufficient, a read-write scope will do as well.
14156    pub fn add_scope<St>(mut self, scope: St) -> UserSettingCseKeypairCreateCall<'a, C>
14157    where
14158        St: AsRef<str>,
14159    {
14160        self._scopes.insert(String::from(scope.as_ref()));
14161        self
14162    }
14163    /// Identifies the authorization scope(s) for the method you are building.
14164    ///
14165    /// See [`Self::add_scope()`] for details.
14166    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingCseKeypairCreateCall<'a, C>
14167    where
14168        I: IntoIterator<Item = St>,
14169        St: AsRef<str>,
14170    {
14171        self._scopes
14172            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
14173        self
14174    }
14175
14176    /// Removes all scopes, and no default scope will be used either.
14177    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
14178    /// for details).
14179    pub fn clear_scopes(mut self) -> UserSettingCseKeypairCreateCall<'a, C> {
14180        self._scopes.clear();
14181        self
14182    }
14183}
14184
14185/// Turns off a client-side encryption key pair. The authenticated user can no longer use the key pair to decrypt incoming CSE message texts or sign outgoing CSE mail. To regain access, use the EnableCseKeyPair to turn on the key pair. After 30 days, you can permanently delete the key pair by using the ObliterateCseKeyPair method.
14186///
14187/// A builder for the *settings.cse.keypairs.disable* method supported by a *user* resource.
14188/// It is not used directly, but through a [`UserMethods`] instance.
14189///
14190/// # Example
14191///
14192/// Instantiate a resource method builder
14193///
14194/// ```test_harness,no_run
14195/// # extern crate hyper;
14196/// # extern crate hyper_rustls;
14197/// # extern crate google_gmail1 as gmail1;
14198/// use gmail1::api::DisableCseKeyPairRequest;
14199/// # async fn dox() {
14200/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
14201///
14202/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
14203/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
14204/// #     secret,
14205/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
14206/// # ).build().await.unwrap();
14207///
14208/// # let client = hyper_util::client::legacy::Client::builder(
14209/// #     hyper_util::rt::TokioExecutor::new()
14210/// # )
14211/// # .build(
14212/// #     hyper_rustls::HttpsConnectorBuilder::new()
14213/// #         .with_native_roots()
14214/// #         .unwrap()
14215/// #         .https_or_http()
14216/// #         .enable_http1()
14217/// #         .build()
14218/// # );
14219/// # let mut hub = Gmail::new(client, auth);
14220/// // As the method needs a request, you would usually fill it with the desired information
14221/// // into the respective structure. Some of the parts shown here might not be applicable !
14222/// // Values shown here are possibly random and not representative !
14223/// let mut req = DisableCseKeyPairRequest::default();
14224///
14225/// // You can configure optional parameters by calling the respective setters at will, and
14226/// // execute the final call using `doit()`.
14227/// // Values shown here are possibly random and not representative !
14228/// let result = hub.users().settings_cse_keypairs_disable(req, "userId", "keyPairId")
14229///              .doit().await;
14230/// # }
14231/// ```
14232pub struct UserSettingCseKeypairDisableCall<'a, C>
14233where
14234    C: 'a,
14235{
14236    hub: &'a Gmail<C>,
14237    _request: DisableCseKeyPairRequest,
14238    _user_id: String,
14239    _key_pair_id: String,
14240    _delegate: Option<&'a mut dyn common::Delegate>,
14241    _additional_params: HashMap<String, String>,
14242    _scopes: BTreeSet<String>,
14243}
14244
14245impl<'a, C> common::CallBuilder for UserSettingCseKeypairDisableCall<'a, C> {}
14246
14247impl<'a, C> UserSettingCseKeypairDisableCall<'a, C>
14248where
14249    C: common::Connector,
14250{
14251    /// Perform the operation you have build so far.
14252    pub async fn doit(mut self) -> common::Result<(common::Response, CseKeyPair)> {
14253        use std::borrow::Cow;
14254        use std::io::{Read, Seek};
14255
14256        use common::{url::Params, ToParts};
14257        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
14258
14259        let mut dd = common::DefaultDelegate;
14260        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
14261        dlg.begin(common::MethodInfo {
14262            id: "gmail.users.settings.cse.keypairs.disable",
14263            http_method: hyper::Method::POST,
14264        });
14265
14266        for &field in ["alt", "userId", "keyPairId"].iter() {
14267            if self._additional_params.contains_key(field) {
14268                dlg.finished(false);
14269                return Err(common::Error::FieldClash(field));
14270            }
14271        }
14272
14273        let mut params = Params::with_capacity(5 + self._additional_params.len());
14274        params.push("userId", self._user_id);
14275        params.push("keyPairId", self._key_pair_id);
14276
14277        params.extend(self._additional_params.iter());
14278
14279        params.push("alt", "json");
14280        let mut url = self.hub._base_url.clone()
14281            + "gmail/v1/users/{userId}/settings/cse/keypairs/{keyPairId}:disable";
14282        if self._scopes.is_empty() {
14283            self._scopes
14284                .insert(Scope::SettingBasic.as_ref().to_string());
14285        }
14286
14287        #[allow(clippy::single_element_loop)]
14288        for &(find_this, param_name) in
14289            [("{userId}", "userId"), ("{keyPairId}", "keyPairId")].iter()
14290        {
14291            url = params.uri_replacement(url, param_name, find_this, false);
14292        }
14293        {
14294            let to_remove = ["keyPairId", "userId"];
14295            params.remove_params(&to_remove);
14296        }
14297
14298        let url = params.parse_with_url(&url);
14299
14300        let mut json_mime_type = mime::APPLICATION_JSON;
14301        let mut request_value_reader = {
14302            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
14303            common::remove_json_null_values(&mut value);
14304            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
14305            serde_json::to_writer(&mut dst, &value).unwrap();
14306            dst
14307        };
14308        let request_size = request_value_reader
14309            .seek(std::io::SeekFrom::End(0))
14310            .unwrap();
14311        request_value_reader
14312            .seek(std::io::SeekFrom::Start(0))
14313            .unwrap();
14314
14315        loop {
14316            let token = match self
14317                .hub
14318                .auth
14319                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
14320                .await
14321            {
14322                Ok(token) => token,
14323                Err(e) => match dlg.token(e) {
14324                    Ok(token) => token,
14325                    Err(e) => {
14326                        dlg.finished(false);
14327                        return Err(common::Error::MissingToken(e));
14328                    }
14329                },
14330            };
14331            request_value_reader
14332                .seek(std::io::SeekFrom::Start(0))
14333                .unwrap();
14334            let mut req_result = {
14335                let client = &self.hub.client;
14336                dlg.pre_request();
14337                let mut req_builder = hyper::Request::builder()
14338                    .method(hyper::Method::POST)
14339                    .uri(url.as_str())
14340                    .header(USER_AGENT, self.hub._user_agent.clone());
14341
14342                if let Some(token) = token.as_ref() {
14343                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
14344                }
14345
14346                let request = req_builder
14347                    .header(CONTENT_TYPE, json_mime_type.to_string())
14348                    .header(CONTENT_LENGTH, request_size as u64)
14349                    .body(common::to_body(
14350                        request_value_reader.get_ref().clone().into(),
14351                    ));
14352
14353                client.request(request.unwrap()).await
14354            };
14355
14356            match req_result {
14357                Err(err) => {
14358                    if let common::Retry::After(d) = dlg.http_error(&err) {
14359                        sleep(d).await;
14360                        continue;
14361                    }
14362                    dlg.finished(false);
14363                    return Err(common::Error::HttpError(err));
14364                }
14365                Ok(res) => {
14366                    let (mut parts, body) = res.into_parts();
14367                    let mut body = common::Body::new(body);
14368                    if !parts.status.is_success() {
14369                        let bytes = common::to_bytes(body).await.unwrap_or_default();
14370                        let error = serde_json::from_str(&common::to_string(&bytes));
14371                        let response = common::to_response(parts, bytes.into());
14372
14373                        if let common::Retry::After(d) =
14374                            dlg.http_failure(&response, error.as_ref().ok())
14375                        {
14376                            sleep(d).await;
14377                            continue;
14378                        }
14379
14380                        dlg.finished(false);
14381
14382                        return Err(match error {
14383                            Ok(value) => common::Error::BadRequest(value),
14384                            _ => common::Error::Failure(response),
14385                        });
14386                    }
14387                    let response = {
14388                        let bytes = common::to_bytes(body).await.unwrap_or_default();
14389                        let encoded = common::to_string(&bytes);
14390                        match serde_json::from_str(&encoded) {
14391                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
14392                            Err(error) => {
14393                                dlg.response_json_decode_error(&encoded, &error);
14394                                return Err(common::Error::JsonDecodeError(
14395                                    encoded.to_string(),
14396                                    error,
14397                                ));
14398                            }
14399                        }
14400                    };
14401
14402                    dlg.finished(true);
14403                    return Ok(response);
14404                }
14405            }
14406        }
14407    }
14408
14409    ///
14410    /// Sets the *request* property to the given value.
14411    ///
14412    /// Even though the property as already been set when instantiating this call,
14413    /// we provide this method for API completeness.
14414    pub fn request(
14415        mut self,
14416        new_value: DisableCseKeyPairRequest,
14417    ) -> UserSettingCseKeypairDisableCall<'a, C> {
14418        self._request = new_value;
14419        self
14420    }
14421    /// The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
14422    ///
14423    /// Sets the *user id* path property to the given value.
14424    ///
14425    /// Even though the property as already been set when instantiating this call,
14426    /// we provide this method for API completeness.
14427    pub fn user_id(mut self, new_value: &str) -> UserSettingCseKeypairDisableCall<'a, C> {
14428        self._user_id = new_value.to_string();
14429        self
14430    }
14431    /// The identifier of the key pair to turn off.
14432    ///
14433    /// Sets the *key pair id* path property to the given value.
14434    ///
14435    /// Even though the property as already been set when instantiating this call,
14436    /// we provide this method for API completeness.
14437    pub fn key_pair_id(mut self, new_value: &str) -> UserSettingCseKeypairDisableCall<'a, C> {
14438        self._key_pair_id = new_value.to_string();
14439        self
14440    }
14441    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
14442    /// while executing the actual API request.
14443    ///
14444    /// ````text
14445    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
14446    /// ````
14447    ///
14448    /// Sets the *delegate* property to the given value.
14449    pub fn delegate(
14450        mut self,
14451        new_value: &'a mut dyn common::Delegate,
14452    ) -> UserSettingCseKeypairDisableCall<'a, C> {
14453        self._delegate = Some(new_value);
14454        self
14455    }
14456
14457    /// Set any additional parameter of the query string used in the request.
14458    /// It should be used to set parameters which are not yet available through their own
14459    /// setters.
14460    ///
14461    /// Please note that this method must not be used to set any of the known parameters
14462    /// which have their own setter method. If done anyway, the request will fail.
14463    ///
14464    /// # Additional Parameters
14465    ///
14466    /// * *$.xgafv* (query-string) - V1 error format.
14467    /// * *access_token* (query-string) - OAuth access token.
14468    /// * *alt* (query-string) - Data format for response.
14469    /// * *callback* (query-string) - JSONP
14470    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
14471    /// * *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.
14472    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
14473    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
14474    /// * *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.
14475    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
14476    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
14477    pub fn param<T>(mut self, name: T, value: T) -> UserSettingCseKeypairDisableCall<'a, C>
14478    where
14479        T: AsRef<str>,
14480    {
14481        self._additional_params
14482            .insert(name.as_ref().to_string(), value.as_ref().to_string());
14483        self
14484    }
14485
14486    /// Identifies the authorization scope for the method you are building.
14487    ///
14488    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
14489    /// [`Scope::SettingBasic`].
14490    ///
14491    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
14492    /// tokens for more than one scope.
14493    ///
14494    /// Usually there is more than one suitable scope to authorize an operation, some of which may
14495    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
14496    /// sufficient, a read-write scope will do as well.
14497    pub fn add_scope<St>(mut self, scope: St) -> UserSettingCseKeypairDisableCall<'a, C>
14498    where
14499        St: AsRef<str>,
14500    {
14501        self._scopes.insert(String::from(scope.as_ref()));
14502        self
14503    }
14504    /// Identifies the authorization scope(s) for the method you are building.
14505    ///
14506    /// See [`Self::add_scope()`] for details.
14507    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingCseKeypairDisableCall<'a, C>
14508    where
14509        I: IntoIterator<Item = St>,
14510        St: AsRef<str>,
14511    {
14512        self._scopes
14513            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
14514        self
14515    }
14516
14517    /// Removes all scopes, and no default scope will be used either.
14518    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
14519    /// for details).
14520    pub fn clear_scopes(mut self) -> UserSettingCseKeypairDisableCall<'a, C> {
14521        self._scopes.clear();
14522        self
14523    }
14524}
14525
14526/// Turns on a client-side encryption key pair that was turned off. The key pair becomes active again for any associated client-side encryption identities.
14527///
14528/// A builder for the *settings.cse.keypairs.enable* method supported by a *user* resource.
14529/// It is not used directly, but through a [`UserMethods`] instance.
14530///
14531/// # Example
14532///
14533/// Instantiate a resource method builder
14534///
14535/// ```test_harness,no_run
14536/// # extern crate hyper;
14537/// # extern crate hyper_rustls;
14538/// # extern crate google_gmail1 as gmail1;
14539/// use gmail1::api::EnableCseKeyPairRequest;
14540/// # async fn dox() {
14541/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
14542///
14543/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
14544/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
14545/// #     secret,
14546/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
14547/// # ).build().await.unwrap();
14548///
14549/// # let client = hyper_util::client::legacy::Client::builder(
14550/// #     hyper_util::rt::TokioExecutor::new()
14551/// # )
14552/// # .build(
14553/// #     hyper_rustls::HttpsConnectorBuilder::new()
14554/// #         .with_native_roots()
14555/// #         .unwrap()
14556/// #         .https_or_http()
14557/// #         .enable_http1()
14558/// #         .build()
14559/// # );
14560/// # let mut hub = Gmail::new(client, auth);
14561/// // As the method needs a request, you would usually fill it with the desired information
14562/// // into the respective structure. Some of the parts shown here might not be applicable !
14563/// // Values shown here are possibly random and not representative !
14564/// let mut req = EnableCseKeyPairRequest::default();
14565///
14566/// // You can configure optional parameters by calling the respective setters at will, and
14567/// // execute the final call using `doit()`.
14568/// // Values shown here are possibly random and not representative !
14569/// let result = hub.users().settings_cse_keypairs_enable(req, "userId", "keyPairId")
14570///              .doit().await;
14571/// # }
14572/// ```
14573pub struct UserSettingCseKeypairEnableCall<'a, C>
14574where
14575    C: 'a,
14576{
14577    hub: &'a Gmail<C>,
14578    _request: EnableCseKeyPairRequest,
14579    _user_id: String,
14580    _key_pair_id: String,
14581    _delegate: Option<&'a mut dyn common::Delegate>,
14582    _additional_params: HashMap<String, String>,
14583    _scopes: BTreeSet<String>,
14584}
14585
14586impl<'a, C> common::CallBuilder for UserSettingCseKeypairEnableCall<'a, C> {}
14587
14588impl<'a, C> UserSettingCseKeypairEnableCall<'a, C>
14589where
14590    C: common::Connector,
14591{
14592    /// Perform the operation you have build so far.
14593    pub async fn doit(mut self) -> common::Result<(common::Response, CseKeyPair)> {
14594        use std::borrow::Cow;
14595        use std::io::{Read, Seek};
14596
14597        use common::{url::Params, ToParts};
14598        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
14599
14600        let mut dd = common::DefaultDelegate;
14601        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
14602        dlg.begin(common::MethodInfo {
14603            id: "gmail.users.settings.cse.keypairs.enable",
14604            http_method: hyper::Method::POST,
14605        });
14606
14607        for &field in ["alt", "userId", "keyPairId"].iter() {
14608            if self._additional_params.contains_key(field) {
14609                dlg.finished(false);
14610                return Err(common::Error::FieldClash(field));
14611            }
14612        }
14613
14614        let mut params = Params::with_capacity(5 + self._additional_params.len());
14615        params.push("userId", self._user_id);
14616        params.push("keyPairId", self._key_pair_id);
14617
14618        params.extend(self._additional_params.iter());
14619
14620        params.push("alt", "json");
14621        let mut url = self.hub._base_url.clone()
14622            + "gmail/v1/users/{userId}/settings/cse/keypairs/{keyPairId}:enable";
14623        if self._scopes.is_empty() {
14624            self._scopes
14625                .insert(Scope::SettingBasic.as_ref().to_string());
14626        }
14627
14628        #[allow(clippy::single_element_loop)]
14629        for &(find_this, param_name) in
14630            [("{userId}", "userId"), ("{keyPairId}", "keyPairId")].iter()
14631        {
14632            url = params.uri_replacement(url, param_name, find_this, false);
14633        }
14634        {
14635            let to_remove = ["keyPairId", "userId"];
14636            params.remove_params(&to_remove);
14637        }
14638
14639        let url = params.parse_with_url(&url);
14640
14641        let mut json_mime_type = mime::APPLICATION_JSON;
14642        let mut request_value_reader = {
14643            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
14644            common::remove_json_null_values(&mut value);
14645            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
14646            serde_json::to_writer(&mut dst, &value).unwrap();
14647            dst
14648        };
14649        let request_size = request_value_reader
14650            .seek(std::io::SeekFrom::End(0))
14651            .unwrap();
14652        request_value_reader
14653            .seek(std::io::SeekFrom::Start(0))
14654            .unwrap();
14655
14656        loop {
14657            let token = match self
14658                .hub
14659                .auth
14660                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
14661                .await
14662            {
14663                Ok(token) => token,
14664                Err(e) => match dlg.token(e) {
14665                    Ok(token) => token,
14666                    Err(e) => {
14667                        dlg.finished(false);
14668                        return Err(common::Error::MissingToken(e));
14669                    }
14670                },
14671            };
14672            request_value_reader
14673                .seek(std::io::SeekFrom::Start(0))
14674                .unwrap();
14675            let mut req_result = {
14676                let client = &self.hub.client;
14677                dlg.pre_request();
14678                let mut req_builder = hyper::Request::builder()
14679                    .method(hyper::Method::POST)
14680                    .uri(url.as_str())
14681                    .header(USER_AGENT, self.hub._user_agent.clone());
14682
14683                if let Some(token) = token.as_ref() {
14684                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
14685                }
14686
14687                let request = req_builder
14688                    .header(CONTENT_TYPE, json_mime_type.to_string())
14689                    .header(CONTENT_LENGTH, request_size as u64)
14690                    .body(common::to_body(
14691                        request_value_reader.get_ref().clone().into(),
14692                    ));
14693
14694                client.request(request.unwrap()).await
14695            };
14696
14697            match req_result {
14698                Err(err) => {
14699                    if let common::Retry::After(d) = dlg.http_error(&err) {
14700                        sleep(d).await;
14701                        continue;
14702                    }
14703                    dlg.finished(false);
14704                    return Err(common::Error::HttpError(err));
14705                }
14706                Ok(res) => {
14707                    let (mut parts, body) = res.into_parts();
14708                    let mut body = common::Body::new(body);
14709                    if !parts.status.is_success() {
14710                        let bytes = common::to_bytes(body).await.unwrap_or_default();
14711                        let error = serde_json::from_str(&common::to_string(&bytes));
14712                        let response = common::to_response(parts, bytes.into());
14713
14714                        if let common::Retry::After(d) =
14715                            dlg.http_failure(&response, error.as_ref().ok())
14716                        {
14717                            sleep(d).await;
14718                            continue;
14719                        }
14720
14721                        dlg.finished(false);
14722
14723                        return Err(match error {
14724                            Ok(value) => common::Error::BadRequest(value),
14725                            _ => common::Error::Failure(response),
14726                        });
14727                    }
14728                    let response = {
14729                        let bytes = common::to_bytes(body).await.unwrap_or_default();
14730                        let encoded = common::to_string(&bytes);
14731                        match serde_json::from_str(&encoded) {
14732                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
14733                            Err(error) => {
14734                                dlg.response_json_decode_error(&encoded, &error);
14735                                return Err(common::Error::JsonDecodeError(
14736                                    encoded.to_string(),
14737                                    error,
14738                                ));
14739                            }
14740                        }
14741                    };
14742
14743                    dlg.finished(true);
14744                    return Ok(response);
14745                }
14746            }
14747        }
14748    }
14749
14750    ///
14751    /// Sets the *request* property to the given value.
14752    ///
14753    /// Even though the property as already been set when instantiating this call,
14754    /// we provide this method for API completeness.
14755    pub fn request(
14756        mut self,
14757        new_value: EnableCseKeyPairRequest,
14758    ) -> UserSettingCseKeypairEnableCall<'a, C> {
14759        self._request = new_value;
14760        self
14761    }
14762    /// The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
14763    ///
14764    /// Sets the *user id* path property to the given value.
14765    ///
14766    /// Even though the property as already been set when instantiating this call,
14767    /// we provide this method for API completeness.
14768    pub fn user_id(mut self, new_value: &str) -> UserSettingCseKeypairEnableCall<'a, C> {
14769        self._user_id = new_value.to_string();
14770        self
14771    }
14772    /// The identifier of the key pair to turn on.
14773    ///
14774    /// Sets the *key pair id* path property to the given value.
14775    ///
14776    /// Even though the property as already been set when instantiating this call,
14777    /// we provide this method for API completeness.
14778    pub fn key_pair_id(mut self, new_value: &str) -> UserSettingCseKeypairEnableCall<'a, C> {
14779        self._key_pair_id = new_value.to_string();
14780        self
14781    }
14782    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
14783    /// while executing the actual API request.
14784    ///
14785    /// ````text
14786    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
14787    /// ````
14788    ///
14789    /// Sets the *delegate* property to the given value.
14790    pub fn delegate(
14791        mut self,
14792        new_value: &'a mut dyn common::Delegate,
14793    ) -> UserSettingCseKeypairEnableCall<'a, C> {
14794        self._delegate = Some(new_value);
14795        self
14796    }
14797
14798    /// Set any additional parameter of the query string used in the request.
14799    /// It should be used to set parameters which are not yet available through their own
14800    /// setters.
14801    ///
14802    /// Please note that this method must not be used to set any of the known parameters
14803    /// which have their own setter method. If done anyway, the request will fail.
14804    ///
14805    /// # Additional Parameters
14806    ///
14807    /// * *$.xgafv* (query-string) - V1 error format.
14808    /// * *access_token* (query-string) - OAuth access token.
14809    /// * *alt* (query-string) - Data format for response.
14810    /// * *callback* (query-string) - JSONP
14811    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
14812    /// * *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.
14813    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
14814    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
14815    /// * *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.
14816    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
14817    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
14818    pub fn param<T>(mut self, name: T, value: T) -> UserSettingCseKeypairEnableCall<'a, C>
14819    where
14820        T: AsRef<str>,
14821    {
14822        self._additional_params
14823            .insert(name.as_ref().to_string(), value.as_ref().to_string());
14824        self
14825    }
14826
14827    /// Identifies the authorization scope for the method you are building.
14828    ///
14829    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
14830    /// [`Scope::SettingBasic`].
14831    ///
14832    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
14833    /// tokens for more than one scope.
14834    ///
14835    /// Usually there is more than one suitable scope to authorize an operation, some of which may
14836    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
14837    /// sufficient, a read-write scope will do as well.
14838    pub fn add_scope<St>(mut self, scope: St) -> UserSettingCseKeypairEnableCall<'a, C>
14839    where
14840        St: AsRef<str>,
14841    {
14842        self._scopes.insert(String::from(scope.as_ref()));
14843        self
14844    }
14845    /// Identifies the authorization scope(s) for the method you are building.
14846    ///
14847    /// See [`Self::add_scope()`] for details.
14848    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingCseKeypairEnableCall<'a, C>
14849    where
14850        I: IntoIterator<Item = St>,
14851        St: AsRef<str>,
14852    {
14853        self._scopes
14854            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
14855        self
14856    }
14857
14858    /// Removes all scopes, and no default scope will be used either.
14859    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
14860    /// for details).
14861    pub fn clear_scopes(mut self) -> UserSettingCseKeypairEnableCall<'a, C> {
14862        self._scopes.clear();
14863        self
14864    }
14865}
14866
14867/// Retrieves an existing client-side encryption key pair.
14868///
14869/// A builder for the *settings.cse.keypairs.get* method supported by a *user* resource.
14870/// It is not used directly, but through a [`UserMethods`] instance.
14871///
14872/// # Example
14873///
14874/// Instantiate a resource method builder
14875///
14876/// ```test_harness,no_run
14877/// # extern crate hyper;
14878/// # extern crate hyper_rustls;
14879/// # extern crate google_gmail1 as gmail1;
14880/// # async fn dox() {
14881/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
14882///
14883/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
14884/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
14885/// #     secret,
14886/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
14887/// # ).build().await.unwrap();
14888///
14889/// # let client = hyper_util::client::legacy::Client::builder(
14890/// #     hyper_util::rt::TokioExecutor::new()
14891/// # )
14892/// # .build(
14893/// #     hyper_rustls::HttpsConnectorBuilder::new()
14894/// #         .with_native_roots()
14895/// #         .unwrap()
14896/// #         .https_or_http()
14897/// #         .enable_http1()
14898/// #         .build()
14899/// # );
14900/// # let mut hub = Gmail::new(client, auth);
14901/// // You can configure optional parameters by calling the respective setters at will, and
14902/// // execute the final call using `doit()`.
14903/// // Values shown here are possibly random and not representative !
14904/// let result = hub.users().settings_cse_keypairs_get("userId", "keyPairId")
14905///              .doit().await;
14906/// # }
14907/// ```
14908pub struct UserSettingCseKeypairGetCall<'a, C>
14909where
14910    C: 'a,
14911{
14912    hub: &'a Gmail<C>,
14913    _user_id: String,
14914    _key_pair_id: String,
14915    _delegate: Option<&'a mut dyn common::Delegate>,
14916    _additional_params: HashMap<String, String>,
14917    _scopes: BTreeSet<String>,
14918}
14919
14920impl<'a, C> common::CallBuilder for UserSettingCseKeypairGetCall<'a, C> {}
14921
14922impl<'a, C> UserSettingCseKeypairGetCall<'a, C>
14923where
14924    C: common::Connector,
14925{
14926    /// Perform the operation you have build so far.
14927    pub async fn doit(mut self) -> common::Result<(common::Response, CseKeyPair)> {
14928        use std::borrow::Cow;
14929        use std::io::{Read, Seek};
14930
14931        use common::{url::Params, ToParts};
14932        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
14933
14934        let mut dd = common::DefaultDelegate;
14935        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
14936        dlg.begin(common::MethodInfo {
14937            id: "gmail.users.settings.cse.keypairs.get",
14938            http_method: hyper::Method::GET,
14939        });
14940
14941        for &field in ["alt", "userId", "keyPairId"].iter() {
14942            if self._additional_params.contains_key(field) {
14943                dlg.finished(false);
14944                return Err(common::Error::FieldClash(field));
14945            }
14946        }
14947
14948        let mut params = Params::with_capacity(4 + self._additional_params.len());
14949        params.push("userId", self._user_id);
14950        params.push("keyPairId", self._key_pair_id);
14951
14952        params.extend(self._additional_params.iter());
14953
14954        params.push("alt", "json");
14955        let mut url = self.hub._base_url.clone()
14956            + "gmail/v1/users/{userId}/settings/cse/keypairs/{keyPairId}";
14957        if self._scopes.is_empty() {
14958            self._scopes.insert(Scope::Readonly.as_ref().to_string());
14959        }
14960
14961        #[allow(clippy::single_element_loop)]
14962        for &(find_this, param_name) in
14963            [("{userId}", "userId"), ("{keyPairId}", "keyPairId")].iter()
14964        {
14965            url = params.uri_replacement(url, param_name, find_this, false);
14966        }
14967        {
14968            let to_remove = ["keyPairId", "userId"];
14969            params.remove_params(&to_remove);
14970        }
14971
14972        let url = params.parse_with_url(&url);
14973
14974        loop {
14975            let token = match self
14976                .hub
14977                .auth
14978                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
14979                .await
14980            {
14981                Ok(token) => token,
14982                Err(e) => match dlg.token(e) {
14983                    Ok(token) => token,
14984                    Err(e) => {
14985                        dlg.finished(false);
14986                        return Err(common::Error::MissingToken(e));
14987                    }
14988                },
14989            };
14990            let mut req_result = {
14991                let client = &self.hub.client;
14992                dlg.pre_request();
14993                let mut req_builder = hyper::Request::builder()
14994                    .method(hyper::Method::GET)
14995                    .uri(url.as_str())
14996                    .header(USER_AGENT, self.hub._user_agent.clone());
14997
14998                if let Some(token) = token.as_ref() {
14999                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
15000                }
15001
15002                let request = req_builder
15003                    .header(CONTENT_LENGTH, 0_u64)
15004                    .body(common::to_body::<String>(None));
15005
15006                client.request(request.unwrap()).await
15007            };
15008
15009            match req_result {
15010                Err(err) => {
15011                    if let common::Retry::After(d) = dlg.http_error(&err) {
15012                        sleep(d).await;
15013                        continue;
15014                    }
15015                    dlg.finished(false);
15016                    return Err(common::Error::HttpError(err));
15017                }
15018                Ok(res) => {
15019                    let (mut parts, body) = res.into_parts();
15020                    let mut body = common::Body::new(body);
15021                    if !parts.status.is_success() {
15022                        let bytes = common::to_bytes(body).await.unwrap_or_default();
15023                        let error = serde_json::from_str(&common::to_string(&bytes));
15024                        let response = common::to_response(parts, bytes.into());
15025
15026                        if let common::Retry::After(d) =
15027                            dlg.http_failure(&response, error.as_ref().ok())
15028                        {
15029                            sleep(d).await;
15030                            continue;
15031                        }
15032
15033                        dlg.finished(false);
15034
15035                        return Err(match error {
15036                            Ok(value) => common::Error::BadRequest(value),
15037                            _ => common::Error::Failure(response),
15038                        });
15039                    }
15040                    let response = {
15041                        let bytes = common::to_bytes(body).await.unwrap_or_default();
15042                        let encoded = common::to_string(&bytes);
15043                        match serde_json::from_str(&encoded) {
15044                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
15045                            Err(error) => {
15046                                dlg.response_json_decode_error(&encoded, &error);
15047                                return Err(common::Error::JsonDecodeError(
15048                                    encoded.to_string(),
15049                                    error,
15050                                ));
15051                            }
15052                        }
15053                    };
15054
15055                    dlg.finished(true);
15056                    return Ok(response);
15057                }
15058            }
15059        }
15060    }
15061
15062    /// The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
15063    ///
15064    /// Sets the *user id* path property to the given value.
15065    ///
15066    /// Even though the property as already been set when instantiating this call,
15067    /// we provide this method for API completeness.
15068    pub fn user_id(mut self, new_value: &str) -> UserSettingCseKeypairGetCall<'a, C> {
15069        self._user_id = new_value.to_string();
15070        self
15071    }
15072    /// The identifier of the key pair to retrieve.
15073    ///
15074    /// Sets the *key pair id* path property to the given value.
15075    ///
15076    /// Even though the property as already been set when instantiating this call,
15077    /// we provide this method for API completeness.
15078    pub fn key_pair_id(mut self, new_value: &str) -> UserSettingCseKeypairGetCall<'a, C> {
15079        self._key_pair_id = new_value.to_string();
15080        self
15081    }
15082    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
15083    /// while executing the actual API request.
15084    ///
15085    /// ````text
15086    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
15087    /// ````
15088    ///
15089    /// Sets the *delegate* property to the given value.
15090    pub fn delegate(
15091        mut self,
15092        new_value: &'a mut dyn common::Delegate,
15093    ) -> UserSettingCseKeypairGetCall<'a, C> {
15094        self._delegate = Some(new_value);
15095        self
15096    }
15097
15098    /// Set any additional parameter of the query string used in the request.
15099    /// It should be used to set parameters which are not yet available through their own
15100    /// setters.
15101    ///
15102    /// Please note that this method must not be used to set any of the known parameters
15103    /// which have their own setter method. If done anyway, the request will fail.
15104    ///
15105    /// # Additional Parameters
15106    ///
15107    /// * *$.xgafv* (query-string) - V1 error format.
15108    /// * *access_token* (query-string) - OAuth access token.
15109    /// * *alt* (query-string) - Data format for response.
15110    /// * *callback* (query-string) - JSONP
15111    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
15112    /// * *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.
15113    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
15114    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
15115    /// * *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.
15116    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
15117    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
15118    pub fn param<T>(mut self, name: T, value: T) -> UserSettingCseKeypairGetCall<'a, C>
15119    where
15120        T: AsRef<str>,
15121    {
15122        self._additional_params
15123            .insert(name.as_ref().to_string(), value.as_ref().to_string());
15124        self
15125    }
15126
15127    /// Identifies the authorization scope for the method you are building.
15128    ///
15129    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
15130    /// [`Scope::Readonly`].
15131    ///
15132    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
15133    /// tokens for more than one scope.
15134    ///
15135    /// Usually there is more than one suitable scope to authorize an operation, some of which may
15136    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
15137    /// sufficient, a read-write scope will do as well.
15138    pub fn add_scope<St>(mut self, scope: St) -> UserSettingCseKeypairGetCall<'a, C>
15139    where
15140        St: AsRef<str>,
15141    {
15142        self._scopes.insert(String::from(scope.as_ref()));
15143        self
15144    }
15145    /// Identifies the authorization scope(s) for the method you are building.
15146    ///
15147    /// See [`Self::add_scope()`] for details.
15148    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingCseKeypairGetCall<'a, C>
15149    where
15150        I: IntoIterator<Item = St>,
15151        St: AsRef<str>,
15152    {
15153        self._scopes
15154            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
15155        self
15156    }
15157
15158    /// Removes all scopes, and no default scope will be used either.
15159    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
15160    /// for details).
15161    pub fn clear_scopes(mut self) -> UserSettingCseKeypairGetCall<'a, C> {
15162        self._scopes.clear();
15163        self
15164    }
15165}
15166
15167/// Lists client-side encryption key pairs for an authenticated user.
15168///
15169/// A builder for the *settings.cse.keypairs.list* method supported by a *user* resource.
15170/// It is not used directly, but through a [`UserMethods`] instance.
15171///
15172/// # Example
15173///
15174/// Instantiate a resource method builder
15175///
15176/// ```test_harness,no_run
15177/// # extern crate hyper;
15178/// # extern crate hyper_rustls;
15179/// # extern crate google_gmail1 as gmail1;
15180/// # async fn dox() {
15181/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
15182///
15183/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
15184/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
15185/// #     secret,
15186/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
15187/// # ).build().await.unwrap();
15188///
15189/// # let client = hyper_util::client::legacy::Client::builder(
15190/// #     hyper_util::rt::TokioExecutor::new()
15191/// # )
15192/// # .build(
15193/// #     hyper_rustls::HttpsConnectorBuilder::new()
15194/// #         .with_native_roots()
15195/// #         .unwrap()
15196/// #         .https_or_http()
15197/// #         .enable_http1()
15198/// #         .build()
15199/// # );
15200/// # let mut hub = Gmail::new(client, auth);
15201/// // You can configure optional parameters by calling the respective setters at will, and
15202/// // execute the final call using `doit()`.
15203/// // Values shown here are possibly random and not representative !
15204/// let result = hub.users().settings_cse_keypairs_list("userId")
15205///              .page_token("tempor")
15206///              .page_size(-32)
15207///              .doit().await;
15208/// # }
15209/// ```
15210pub struct UserSettingCseKeypairListCall<'a, C>
15211where
15212    C: 'a,
15213{
15214    hub: &'a Gmail<C>,
15215    _user_id: String,
15216    _page_token: Option<String>,
15217    _page_size: Option<i32>,
15218    _delegate: Option<&'a mut dyn common::Delegate>,
15219    _additional_params: HashMap<String, String>,
15220    _scopes: BTreeSet<String>,
15221}
15222
15223impl<'a, C> common::CallBuilder for UserSettingCseKeypairListCall<'a, C> {}
15224
15225impl<'a, C> UserSettingCseKeypairListCall<'a, C>
15226where
15227    C: common::Connector,
15228{
15229    /// Perform the operation you have build so far.
15230    pub async fn doit(mut self) -> common::Result<(common::Response, ListCseKeyPairsResponse)> {
15231        use std::borrow::Cow;
15232        use std::io::{Read, Seek};
15233
15234        use common::{url::Params, ToParts};
15235        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
15236
15237        let mut dd = common::DefaultDelegate;
15238        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
15239        dlg.begin(common::MethodInfo {
15240            id: "gmail.users.settings.cse.keypairs.list",
15241            http_method: hyper::Method::GET,
15242        });
15243
15244        for &field in ["alt", "userId", "pageToken", "pageSize"].iter() {
15245            if self._additional_params.contains_key(field) {
15246                dlg.finished(false);
15247                return Err(common::Error::FieldClash(field));
15248            }
15249        }
15250
15251        let mut params = Params::with_capacity(5 + self._additional_params.len());
15252        params.push("userId", self._user_id);
15253        if let Some(value) = self._page_token.as_ref() {
15254            params.push("pageToken", value);
15255        }
15256        if let Some(value) = self._page_size.as_ref() {
15257            params.push("pageSize", value.to_string());
15258        }
15259
15260        params.extend(self._additional_params.iter());
15261
15262        params.push("alt", "json");
15263        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/cse/keypairs";
15264        if self._scopes.is_empty() {
15265            self._scopes.insert(Scope::Readonly.as_ref().to_string());
15266        }
15267
15268        #[allow(clippy::single_element_loop)]
15269        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
15270            url = params.uri_replacement(url, param_name, find_this, false);
15271        }
15272        {
15273            let to_remove = ["userId"];
15274            params.remove_params(&to_remove);
15275        }
15276
15277        let url = params.parse_with_url(&url);
15278
15279        loop {
15280            let token = match self
15281                .hub
15282                .auth
15283                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
15284                .await
15285            {
15286                Ok(token) => token,
15287                Err(e) => match dlg.token(e) {
15288                    Ok(token) => token,
15289                    Err(e) => {
15290                        dlg.finished(false);
15291                        return Err(common::Error::MissingToken(e));
15292                    }
15293                },
15294            };
15295            let mut req_result = {
15296                let client = &self.hub.client;
15297                dlg.pre_request();
15298                let mut req_builder = hyper::Request::builder()
15299                    .method(hyper::Method::GET)
15300                    .uri(url.as_str())
15301                    .header(USER_AGENT, self.hub._user_agent.clone());
15302
15303                if let Some(token) = token.as_ref() {
15304                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
15305                }
15306
15307                let request = req_builder
15308                    .header(CONTENT_LENGTH, 0_u64)
15309                    .body(common::to_body::<String>(None));
15310
15311                client.request(request.unwrap()).await
15312            };
15313
15314            match req_result {
15315                Err(err) => {
15316                    if let common::Retry::After(d) = dlg.http_error(&err) {
15317                        sleep(d).await;
15318                        continue;
15319                    }
15320                    dlg.finished(false);
15321                    return Err(common::Error::HttpError(err));
15322                }
15323                Ok(res) => {
15324                    let (mut parts, body) = res.into_parts();
15325                    let mut body = common::Body::new(body);
15326                    if !parts.status.is_success() {
15327                        let bytes = common::to_bytes(body).await.unwrap_or_default();
15328                        let error = serde_json::from_str(&common::to_string(&bytes));
15329                        let response = common::to_response(parts, bytes.into());
15330
15331                        if let common::Retry::After(d) =
15332                            dlg.http_failure(&response, error.as_ref().ok())
15333                        {
15334                            sleep(d).await;
15335                            continue;
15336                        }
15337
15338                        dlg.finished(false);
15339
15340                        return Err(match error {
15341                            Ok(value) => common::Error::BadRequest(value),
15342                            _ => common::Error::Failure(response),
15343                        });
15344                    }
15345                    let response = {
15346                        let bytes = common::to_bytes(body).await.unwrap_or_default();
15347                        let encoded = common::to_string(&bytes);
15348                        match serde_json::from_str(&encoded) {
15349                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
15350                            Err(error) => {
15351                                dlg.response_json_decode_error(&encoded, &error);
15352                                return Err(common::Error::JsonDecodeError(
15353                                    encoded.to_string(),
15354                                    error,
15355                                ));
15356                            }
15357                        }
15358                    };
15359
15360                    dlg.finished(true);
15361                    return Ok(response);
15362                }
15363            }
15364        }
15365    }
15366
15367    /// The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
15368    ///
15369    /// Sets the *user id* path property to the given value.
15370    ///
15371    /// Even though the property as already been set when instantiating this call,
15372    /// we provide this method for API completeness.
15373    pub fn user_id(mut self, new_value: &str) -> UserSettingCseKeypairListCall<'a, C> {
15374        self._user_id = new_value.to_string();
15375        self
15376    }
15377    /// Pagination token indicating which page of key pairs to return. If the token is not supplied, then the API will return the first page of results.
15378    ///
15379    /// Sets the *page token* query property to the given value.
15380    pub fn page_token(mut self, new_value: &str) -> UserSettingCseKeypairListCall<'a, C> {
15381        self._page_token = Some(new_value.to_string());
15382        self
15383    }
15384    /// The number of key pairs to return. If not provided, the page size will default to 20 entries.
15385    ///
15386    /// Sets the *page size* query property to the given value.
15387    pub fn page_size(mut self, new_value: i32) -> UserSettingCseKeypairListCall<'a, C> {
15388        self._page_size = Some(new_value);
15389        self
15390    }
15391    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
15392    /// while executing the actual API request.
15393    ///
15394    /// ````text
15395    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
15396    /// ````
15397    ///
15398    /// Sets the *delegate* property to the given value.
15399    pub fn delegate(
15400        mut self,
15401        new_value: &'a mut dyn common::Delegate,
15402    ) -> UserSettingCseKeypairListCall<'a, C> {
15403        self._delegate = Some(new_value);
15404        self
15405    }
15406
15407    /// Set any additional parameter of the query string used in the request.
15408    /// It should be used to set parameters which are not yet available through their own
15409    /// setters.
15410    ///
15411    /// Please note that this method must not be used to set any of the known parameters
15412    /// which have their own setter method. If done anyway, the request will fail.
15413    ///
15414    /// # Additional Parameters
15415    ///
15416    /// * *$.xgafv* (query-string) - V1 error format.
15417    /// * *access_token* (query-string) - OAuth access token.
15418    /// * *alt* (query-string) - Data format for response.
15419    /// * *callback* (query-string) - JSONP
15420    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
15421    /// * *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.
15422    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
15423    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
15424    /// * *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.
15425    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
15426    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
15427    pub fn param<T>(mut self, name: T, value: T) -> UserSettingCseKeypairListCall<'a, C>
15428    where
15429        T: AsRef<str>,
15430    {
15431        self._additional_params
15432            .insert(name.as_ref().to_string(), value.as_ref().to_string());
15433        self
15434    }
15435
15436    /// Identifies the authorization scope for the method you are building.
15437    ///
15438    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
15439    /// [`Scope::Readonly`].
15440    ///
15441    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
15442    /// tokens for more than one scope.
15443    ///
15444    /// Usually there is more than one suitable scope to authorize an operation, some of which may
15445    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
15446    /// sufficient, a read-write scope will do as well.
15447    pub fn add_scope<St>(mut self, scope: St) -> UserSettingCseKeypairListCall<'a, C>
15448    where
15449        St: AsRef<str>,
15450    {
15451        self._scopes.insert(String::from(scope.as_ref()));
15452        self
15453    }
15454    /// Identifies the authorization scope(s) for the method you are building.
15455    ///
15456    /// See [`Self::add_scope()`] for details.
15457    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingCseKeypairListCall<'a, C>
15458    where
15459        I: IntoIterator<Item = St>,
15460        St: AsRef<str>,
15461    {
15462        self._scopes
15463            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
15464        self
15465    }
15466
15467    /// Removes all scopes, and no default scope will be used either.
15468    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
15469    /// for details).
15470    pub fn clear_scopes(mut self) -> UserSettingCseKeypairListCall<'a, C> {
15471        self._scopes.clear();
15472        self
15473    }
15474}
15475
15476/// Deletes a client-side encryption key pair permanently and immediately. You can only permanently delete key pairs that have been turned off for more than 30 days. To turn off a key pair, use the DisableCseKeyPair method. Gmail can't restore or decrypt any messages that were encrypted by an obliterated key. Authenticated users and Google Workspace administrators lose access to reading the encrypted messages.
15477///
15478/// A builder for the *settings.cse.keypairs.obliterate* method supported by a *user* resource.
15479/// It is not used directly, but through a [`UserMethods`] instance.
15480///
15481/// # Example
15482///
15483/// Instantiate a resource method builder
15484///
15485/// ```test_harness,no_run
15486/// # extern crate hyper;
15487/// # extern crate hyper_rustls;
15488/// # extern crate google_gmail1 as gmail1;
15489/// use gmail1::api::ObliterateCseKeyPairRequest;
15490/// # async fn dox() {
15491/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
15492///
15493/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
15494/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
15495/// #     secret,
15496/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
15497/// # ).build().await.unwrap();
15498///
15499/// # let client = hyper_util::client::legacy::Client::builder(
15500/// #     hyper_util::rt::TokioExecutor::new()
15501/// # )
15502/// # .build(
15503/// #     hyper_rustls::HttpsConnectorBuilder::new()
15504/// #         .with_native_roots()
15505/// #         .unwrap()
15506/// #         .https_or_http()
15507/// #         .enable_http1()
15508/// #         .build()
15509/// # );
15510/// # let mut hub = Gmail::new(client, auth);
15511/// // As the method needs a request, you would usually fill it with the desired information
15512/// // into the respective structure. Some of the parts shown here might not be applicable !
15513/// // Values shown here are possibly random and not representative !
15514/// let mut req = ObliterateCseKeyPairRequest::default();
15515///
15516/// // You can configure optional parameters by calling the respective setters at will, and
15517/// // execute the final call using `doit()`.
15518/// // Values shown here are possibly random and not representative !
15519/// let result = hub.users().settings_cse_keypairs_obliterate(req, "userId", "keyPairId")
15520///              .doit().await;
15521/// # }
15522/// ```
15523pub struct UserSettingCseKeypairObliterateCall<'a, C>
15524where
15525    C: 'a,
15526{
15527    hub: &'a Gmail<C>,
15528    _request: ObliterateCseKeyPairRequest,
15529    _user_id: String,
15530    _key_pair_id: String,
15531    _delegate: Option<&'a mut dyn common::Delegate>,
15532    _additional_params: HashMap<String, String>,
15533    _scopes: BTreeSet<String>,
15534}
15535
15536impl<'a, C> common::CallBuilder for UserSettingCseKeypairObliterateCall<'a, C> {}
15537
15538impl<'a, C> UserSettingCseKeypairObliterateCall<'a, C>
15539where
15540    C: common::Connector,
15541{
15542    /// Perform the operation you have build so far.
15543    pub async fn doit(mut self) -> common::Result<common::Response> {
15544        use std::borrow::Cow;
15545        use std::io::{Read, Seek};
15546
15547        use common::{url::Params, ToParts};
15548        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
15549
15550        let mut dd = common::DefaultDelegate;
15551        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
15552        dlg.begin(common::MethodInfo {
15553            id: "gmail.users.settings.cse.keypairs.obliterate",
15554            http_method: hyper::Method::POST,
15555        });
15556
15557        for &field in ["userId", "keyPairId"].iter() {
15558            if self._additional_params.contains_key(field) {
15559                dlg.finished(false);
15560                return Err(common::Error::FieldClash(field));
15561            }
15562        }
15563
15564        let mut params = Params::with_capacity(4 + self._additional_params.len());
15565        params.push("userId", self._user_id);
15566        params.push("keyPairId", self._key_pair_id);
15567
15568        params.extend(self._additional_params.iter());
15569
15570        let mut url = self.hub._base_url.clone()
15571            + "gmail/v1/users/{userId}/settings/cse/keypairs/{keyPairId}:obliterate";
15572        if self._scopes.is_empty() {
15573            self._scopes
15574                .insert(Scope::SettingBasic.as_ref().to_string());
15575        }
15576
15577        #[allow(clippy::single_element_loop)]
15578        for &(find_this, param_name) in
15579            [("{userId}", "userId"), ("{keyPairId}", "keyPairId")].iter()
15580        {
15581            url = params.uri_replacement(url, param_name, find_this, false);
15582        }
15583        {
15584            let to_remove = ["keyPairId", "userId"];
15585            params.remove_params(&to_remove);
15586        }
15587
15588        let url = params.parse_with_url(&url);
15589
15590        let mut json_mime_type = mime::APPLICATION_JSON;
15591        let mut request_value_reader = {
15592            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
15593            common::remove_json_null_values(&mut value);
15594            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
15595            serde_json::to_writer(&mut dst, &value).unwrap();
15596            dst
15597        };
15598        let request_size = request_value_reader
15599            .seek(std::io::SeekFrom::End(0))
15600            .unwrap();
15601        request_value_reader
15602            .seek(std::io::SeekFrom::Start(0))
15603            .unwrap();
15604
15605        loop {
15606            let token = match self
15607                .hub
15608                .auth
15609                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
15610                .await
15611            {
15612                Ok(token) => token,
15613                Err(e) => match dlg.token(e) {
15614                    Ok(token) => token,
15615                    Err(e) => {
15616                        dlg.finished(false);
15617                        return Err(common::Error::MissingToken(e));
15618                    }
15619                },
15620            };
15621            request_value_reader
15622                .seek(std::io::SeekFrom::Start(0))
15623                .unwrap();
15624            let mut req_result = {
15625                let client = &self.hub.client;
15626                dlg.pre_request();
15627                let mut req_builder = hyper::Request::builder()
15628                    .method(hyper::Method::POST)
15629                    .uri(url.as_str())
15630                    .header(USER_AGENT, self.hub._user_agent.clone());
15631
15632                if let Some(token) = token.as_ref() {
15633                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
15634                }
15635
15636                let request = req_builder
15637                    .header(CONTENT_TYPE, json_mime_type.to_string())
15638                    .header(CONTENT_LENGTH, request_size as u64)
15639                    .body(common::to_body(
15640                        request_value_reader.get_ref().clone().into(),
15641                    ));
15642
15643                client.request(request.unwrap()).await
15644            };
15645
15646            match req_result {
15647                Err(err) => {
15648                    if let common::Retry::After(d) = dlg.http_error(&err) {
15649                        sleep(d).await;
15650                        continue;
15651                    }
15652                    dlg.finished(false);
15653                    return Err(common::Error::HttpError(err));
15654                }
15655                Ok(res) => {
15656                    let (mut parts, body) = res.into_parts();
15657                    let mut body = common::Body::new(body);
15658                    if !parts.status.is_success() {
15659                        let bytes = common::to_bytes(body).await.unwrap_or_default();
15660                        let error = serde_json::from_str(&common::to_string(&bytes));
15661                        let response = common::to_response(parts, bytes.into());
15662
15663                        if let common::Retry::After(d) =
15664                            dlg.http_failure(&response, error.as_ref().ok())
15665                        {
15666                            sleep(d).await;
15667                            continue;
15668                        }
15669
15670                        dlg.finished(false);
15671
15672                        return Err(match error {
15673                            Ok(value) => common::Error::BadRequest(value),
15674                            _ => common::Error::Failure(response),
15675                        });
15676                    }
15677                    let response = common::Response::from_parts(parts, body);
15678
15679                    dlg.finished(true);
15680                    return Ok(response);
15681                }
15682            }
15683        }
15684    }
15685
15686    ///
15687    /// Sets the *request* property to the given value.
15688    ///
15689    /// Even though the property as already been set when instantiating this call,
15690    /// we provide this method for API completeness.
15691    pub fn request(
15692        mut self,
15693        new_value: ObliterateCseKeyPairRequest,
15694    ) -> UserSettingCseKeypairObliterateCall<'a, C> {
15695        self._request = new_value;
15696        self
15697    }
15698    /// The requester's primary email address. To indicate the authenticated user, you can use the special value `me`.
15699    ///
15700    /// Sets the *user id* path property to the given value.
15701    ///
15702    /// Even though the property as already been set when instantiating this call,
15703    /// we provide this method for API completeness.
15704    pub fn user_id(mut self, new_value: &str) -> UserSettingCseKeypairObliterateCall<'a, C> {
15705        self._user_id = new_value.to_string();
15706        self
15707    }
15708    /// The identifier of the key pair to obliterate.
15709    ///
15710    /// Sets the *key pair id* path property to the given value.
15711    ///
15712    /// Even though the property as already been set when instantiating this call,
15713    /// we provide this method for API completeness.
15714    pub fn key_pair_id(mut self, new_value: &str) -> UserSettingCseKeypairObliterateCall<'a, C> {
15715        self._key_pair_id = new_value.to_string();
15716        self
15717    }
15718    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
15719    /// while executing the actual API request.
15720    ///
15721    /// ````text
15722    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
15723    /// ````
15724    ///
15725    /// Sets the *delegate* property to the given value.
15726    pub fn delegate(
15727        mut self,
15728        new_value: &'a mut dyn common::Delegate,
15729    ) -> UserSettingCseKeypairObliterateCall<'a, C> {
15730        self._delegate = Some(new_value);
15731        self
15732    }
15733
15734    /// Set any additional parameter of the query string used in the request.
15735    /// It should be used to set parameters which are not yet available through their own
15736    /// setters.
15737    ///
15738    /// Please note that this method must not be used to set any of the known parameters
15739    /// which have their own setter method. If done anyway, the request will fail.
15740    ///
15741    /// # Additional Parameters
15742    ///
15743    /// * *$.xgafv* (query-string) - V1 error format.
15744    /// * *access_token* (query-string) - OAuth access token.
15745    /// * *alt* (query-string) - Data format for response.
15746    /// * *callback* (query-string) - JSONP
15747    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
15748    /// * *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.
15749    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
15750    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
15751    /// * *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.
15752    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
15753    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
15754    pub fn param<T>(mut self, name: T, value: T) -> UserSettingCseKeypairObliterateCall<'a, C>
15755    where
15756        T: AsRef<str>,
15757    {
15758        self._additional_params
15759            .insert(name.as_ref().to_string(), value.as_ref().to_string());
15760        self
15761    }
15762
15763    /// Identifies the authorization scope for the method you are building.
15764    ///
15765    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
15766    /// [`Scope::SettingBasic`].
15767    ///
15768    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
15769    /// tokens for more than one scope.
15770    ///
15771    /// Usually there is more than one suitable scope to authorize an operation, some of which may
15772    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
15773    /// sufficient, a read-write scope will do as well.
15774    pub fn add_scope<St>(mut self, scope: St) -> UserSettingCseKeypairObliterateCall<'a, C>
15775    where
15776        St: AsRef<str>,
15777    {
15778        self._scopes.insert(String::from(scope.as_ref()));
15779        self
15780    }
15781    /// Identifies the authorization scope(s) for the method you are building.
15782    ///
15783    /// See [`Self::add_scope()`] for details.
15784    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingCseKeypairObliterateCall<'a, C>
15785    where
15786        I: IntoIterator<Item = St>,
15787        St: AsRef<str>,
15788    {
15789        self._scopes
15790            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
15791        self
15792    }
15793
15794    /// Removes all scopes, and no default scope will be used either.
15795    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
15796    /// for details).
15797    pub fn clear_scopes(mut self) -> UserSettingCseKeypairObliterateCall<'a, C> {
15798        self._scopes.clear();
15799        self
15800    }
15801}
15802
15803/// Adds a delegate with its verification status set directly to `accepted`, without sending any verification email. The delegate user must be a member of the same Google Workspace organization as the delegator user. Gmail imposes limitations on the number of delegates and delegators each user in a Google Workspace organization can have. These limits depend on your organization, but in general each user can have up to 25 delegates and up to 10 delegators. Note that a delegate user must be referred to by their primary email address, and not an email alias. Also note that when a new delegate is created, there may be up to a one minute delay before the new delegate is available for use. This method is only available to service account clients that have been delegated domain-wide authority.
15804///
15805/// A builder for the *settings.delegates.create* method supported by a *user* resource.
15806/// It is not used directly, but through a [`UserMethods`] instance.
15807///
15808/// # Example
15809///
15810/// Instantiate a resource method builder
15811///
15812/// ```test_harness,no_run
15813/// # extern crate hyper;
15814/// # extern crate hyper_rustls;
15815/// # extern crate google_gmail1 as gmail1;
15816/// use gmail1::api::Delegate;
15817/// # async fn dox() {
15818/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
15819///
15820/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
15821/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
15822/// #     secret,
15823/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
15824/// # ).build().await.unwrap();
15825///
15826/// # let client = hyper_util::client::legacy::Client::builder(
15827/// #     hyper_util::rt::TokioExecutor::new()
15828/// # )
15829/// # .build(
15830/// #     hyper_rustls::HttpsConnectorBuilder::new()
15831/// #         .with_native_roots()
15832/// #         .unwrap()
15833/// #         .https_or_http()
15834/// #         .enable_http1()
15835/// #         .build()
15836/// # );
15837/// # let mut hub = Gmail::new(client, auth);
15838/// // As the method needs a request, you would usually fill it with the desired information
15839/// // into the respective structure. Some of the parts shown here might not be applicable !
15840/// // Values shown here are possibly random and not representative !
15841/// let mut req = Delegate::default();
15842///
15843/// // You can configure optional parameters by calling the respective setters at will, and
15844/// // execute the final call using `doit()`.
15845/// // Values shown here are possibly random and not representative !
15846/// let result = hub.users().settings_delegates_create(req, "userId")
15847///              .doit().await;
15848/// # }
15849/// ```
15850pub struct UserSettingDelegateCreateCall<'a, C>
15851where
15852    C: 'a,
15853{
15854    hub: &'a Gmail<C>,
15855    _request: Delegate,
15856    _user_id: String,
15857    _delegate: Option<&'a mut dyn common::Delegate>,
15858    _additional_params: HashMap<String, String>,
15859    _scopes: BTreeSet<String>,
15860}
15861
15862impl<'a, C> common::CallBuilder for UserSettingDelegateCreateCall<'a, C> {}
15863
15864impl<'a, C> UserSettingDelegateCreateCall<'a, C>
15865where
15866    C: common::Connector,
15867{
15868    /// Perform the operation you have build so far.
15869    pub async fn doit(mut self) -> common::Result<(common::Response, Delegate)> {
15870        use std::borrow::Cow;
15871        use std::io::{Read, Seek};
15872
15873        use common::{url::Params, ToParts};
15874        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
15875
15876        let mut dd = common::DefaultDelegate;
15877        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
15878        dlg.begin(common::MethodInfo {
15879            id: "gmail.users.settings.delegates.create",
15880            http_method: hyper::Method::POST,
15881        });
15882
15883        for &field in ["alt", "userId"].iter() {
15884            if self._additional_params.contains_key(field) {
15885                dlg.finished(false);
15886                return Err(common::Error::FieldClash(field));
15887            }
15888        }
15889
15890        let mut params = Params::with_capacity(4 + self._additional_params.len());
15891        params.push("userId", self._user_id);
15892
15893        params.extend(self._additional_params.iter());
15894
15895        params.push("alt", "json");
15896        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/delegates";
15897        if self._scopes.is_empty() {
15898            self._scopes
15899                .insert(Scope::SettingSharing.as_ref().to_string());
15900        }
15901
15902        #[allow(clippy::single_element_loop)]
15903        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
15904            url = params.uri_replacement(url, param_name, find_this, false);
15905        }
15906        {
15907            let to_remove = ["userId"];
15908            params.remove_params(&to_remove);
15909        }
15910
15911        let url = params.parse_with_url(&url);
15912
15913        let mut json_mime_type = mime::APPLICATION_JSON;
15914        let mut request_value_reader = {
15915            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
15916            common::remove_json_null_values(&mut value);
15917            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
15918            serde_json::to_writer(&mut dst, &value).unwrap();
15919            dst
15920        };
15921        let request_size = request_value_reader
15922            .seek(std::io::SeekFrom::End(0))
15923            .unwrap();
15924        request_value_reader
15925            .seek(std::io::SeekFrom::Start(0))
15926            .unwrap();
15927
15928        loop {
15929            let token = match self
15930                .hub
15931                .auth
15932                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
15933                .await
15934            {
15935                Ok(token) => token,
15936                Err(e) => match dlg.token(e) {
15937                    Ok(token) => token,
15938                    Err(e) => {
15939                        dlg.finished(false);
15940                        return Err(common::Error::MissingToken(e));
15941                    }
15942                },
15943            };
15944            request_value_reader
15945                .seek(std::io::SeekFrom::Start(0))
15946                .unwrap();
15947            let mut req_result = {
15948                let client = &self.hub.client;
15949                dlg.pre_request();
15950                let mut req_builder = hyper::Request::builder()
15951                    .method(hyper::Method::POST)
15952                    .uri(url.as_str())
15953                    .header(USER_AGENT, self.hub._user_agent.clone());
15954
15955                if let Some(token) = token.as_ref() {
15956                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
15957                }
15958
15959                let request = req_builder
15960                    .header(CONTENT_TYPE, json_mime_type.to_string())
15961                    .header(CONTENT_LENGTH, request_size as u64)
15962                    .body(common::to_body(
15963                        request_value_reader.get_ref().clone().into(),
15964                    ));
15965
15966                client.request(request.unwrap()).await
15967            };
15968
15969            match req_result {
15970                Err(err) => {
15971                    if let common::Retry::After(d) = dlg.http_error(&err) {
15972                        sleep(d).await;
15973                        continue;
15974                    }
15975                    dlg.finished(false);
15976                    return Err(common::Error::HttpError(err));
15977                }
15978                Ok(res) => {
15979                    let (mut parts, body) = res.into_parts();
15980                    let mut body = common::Body::new(body);
15981                    if !parts.status.is_success() {
15982                        let bytes = common::to_bytes(body).await.unwrap_or_default();
15983                        let error = serde_json::from_str(&common::to_string(&bytes));
15984                        let response = common::to_response(parts, bytes.into());
15985
15986                        if let common::Retry::After(d) =
15987                            dlg.http_failure(&response, error.as_ref().ok())
15988                        {
15989                            sleep(d).await;
15990                            continue;
15991                        }
15992
15993                        dlg.finished(false);
15994
15995                        return Err(match error {
15996                            Ok(value) => common::Error::BadRequest(value),
15997                            _ => common::Error::Failure(response),
15998                        });
15999                    }
16000                    let response = {
16001                        let bytes = common::to_bytes(body).await.unwrap_or_default();
16002                        let encoded = common::to_string(&bytes);
16003                        match serde_json::from_str(&encoded) {
16004                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
16005                            Err(error) => {
16006                                dlg.response_json_decode_error(&encoded, &error);
16007                                return Err(common::Error::JsonDecodeError(
16008                                    encoded.to_string(),
16009                                    error,
16010                                ));
16011                            }
16012                        }
16013                    };
16014
16015                    dlg.finished(true);
16016                    return Ok(response);
16017                }
16018            }
16019        }
16020    }
16021
16022    ///
16023    /// Sets the *request* property to the given value.
16024    ///
16025    /// Even though the property as already been set when instantiating this call,
16026    /// we provide this method for API completeness.
16027    pub fn request(mut self, new_value: Delegate) -> UserSettingDelegateCreateCall<'a, C> {
16028        self._request = new_value;
16029        self
16030    }
16031    /// User's email address. The special value "me" can be used to indicate the authenticated user.
16032    ///
16033    /// Sets the *user id* path property to the given value.
16034    ///
16035    /// Even though the property as already been set when instantiating this call,
16036    /// we provide this method for API completeness.
16037    pub fn user_id(mut self, new_value: &str) -> UserSettingDelegateCreateCall<'a, C> {
16038        self._user_id = new_value.to_string();
16039        self
16040    }
16041    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
16042    /// while executing the actual API request.
16043    ///
16044    /// ````text
16045    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
16046    /// ````
16047    ///
16048    /// Sets the *delegate* property to the given value.
16049    pub fn delegate(
16050        mut self,
16051        new_value: &'a mut dyn common::Delegate,
16052    ) -> UserSettingDelegateCreateCall<'a, C> {
16053        self._delegate = Some(new_value);
16054        self
16055    }
16056
16057    /// Set any additional parameter of the query string used in the request.
16058    /// It should be used to set parameters which are not yet available through their own
16059    /// setters.
16060    ///
16061    /// Please note that this method must not be used to set any of the known parameters
16062    /// which have their own setter method. If done anyway, the request will fail.
16063    ///
16064    /// # Additional Parameters
16065    ///
16066    /// * *$.xgafv* (query-string) - V1 error format.
16067    /// * *access_token* (query-string) - OAuth access token.
16068    /// * *alt* (query-string) - Data format for response.
16069    /// * *callback* (query-string) - JSONP
16070    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
16071    /// * *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.
16072    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
16073    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
16074    /// * *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.
16075    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
16076    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
16077    pub fn param<T>(mut self, name: T, value: T) -> UserSettingDelegateCreateCall<'a, C>
16078    where
16079        T: AsRef<str>,
16080    {
16081        self._additional_params
16082            .insert(name.as_ref().to_string(), value.as_ref().to_string());
16083        self
16084    }
16085
16086    /// Identifies the authorization scope for the method you are building.
16087    ///
16088    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
16089    /// [`Scope::SettingSharing`].
16090    ///
16091    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
16092    /// tokens for more than one scope.
16093    ///
16094    /// Usually there is more than one suitable scope to authorize an operation, some of which may
16095    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
16096    /// sufficient, a read-write scope will do as well.
16097    pub fn add_scope<St>(mut self, scope: St) -> UserSettingDelegateCreateCall<'a, C>
16098    where
16099        St: AsRef<str>,
16100    {
16101        self._scopes.insert(String::from(scope.as_ref()));
16102        self
16103    }
16104    /// Identifies the authorization scope(s) for the method you are building.
16105    ///
16106    /// See [`Self::add_scope()`] for details.
16107    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingDelegateCreateCall<'a, C>
16108    where
16109        I: IntoIterator<Item = St>,
16110        St: AsRef<str>,
16111    {
16112        self._scopes
16113            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
16114        self
16115    }
16116
16117    /// Removes all scopes, and no default scope will be used either.
16118    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
16119    /// for details).
16120    pub fn clear_scopes(mut self) -> UserSettingDelegateCreateCall<'a, C> {
16121        self._scopes.clear();
16122        self
16123    }
16124}
16125
16126/// Removes the specified delegate (which can be of any verification status), and revokes any verification that may have been required for using it. Note that a delegate user must be referred to by their primary email address, and not an email alias. This method is only available to service account clients that have been delegated domain-wide authority.
16127///
16128/// A builder for the *settings.delegates.delete* method supported by a *user* resource.
16129/// It is not used directly, but through a [`UserMethods`] instance.
16130///
16131/// # Example
16132///
16133/// Instantiate a resource method builder
16134///
16135/// ```test_harness,no_run
16136/// # extern crate hyper;
16137/// # extern crate hyper_rustls;
16138/// # extern crate google_gmail1 as gmail1;
16139/// # async fn dox() {
16140/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
16141///
16142/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
16143/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
16144/// #     secret,
16145/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
16146/// # ).build().await.unwrap();
16147///
16148/// # let client = hyper_util::client::legacy::Client::builder(
16149/// #     hyper_util::rt::TokioExecutor::new()
16150/// # )
16151/// # .build(
16152/// #     hyper_rustls::HttpsConnectorBuilder::new()
16153/// #         .with_native_roots()
16154/// #         .unwrap()
16155/// #         .https_or_http()
16156/// #         .enable_http1()
16157/// #         .build()
16158/// # );
16159/// # let mut hub = Gmail::new(client, auth);
16160/// // You can configure optional parameters by calling the respective setters at will, and
16161/// // execute the final call using `doit()`.
16162/// // Values shown here are possibly random and not representative !
16163/// let result = hub.users().settings_delegates_delete("userId", "delegateEmail")
16164///              .doit().await;
16165/// # }
16166/// ```
16167pub struct UserSettingDelegateDeleteCall<'a, C>
16168where
16169    C: 'a,
16170{
16171    hub: &'a Gmail<C>,
16172    _user_id: String,
16173    _delegate_email: String,
16174    _delegate: Option<&'a mut dyn common::Delegate>,
16175    _additional_params: HashMap<String, String>,
16176    _scopes: BTreeSet<String>,
16177}
16178
16179impl<'a, C> common::CallBuilder for UserSettingDelegateDeleteCall<'a, C> {}
16180
16181impl<'a, C> UserSettingDelegateDeleteCall<'a, C>
16182where
16183    C: common::Connector,
16184{
16185    /// Perform the operation you have build so far.
16186    pub async fn doit(mut self) -> common::Result<common::Response> {
16187        use std::borrow::Cow;
16188        use std::io::{Read, Seek};
16189
16190        use common::{url::Params, ToParts};
16191        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
16192
16193        let mut dd = common::DefaultDelegate;
16194        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
16195        dlg.begin(common::MethodInfo {
16196            id: "gmail.users.settings.delegates.delete",
16197            http_method: hyper::Method::DELETE,
16198        });
16199
16200        for &field in ["userId", "delegateEmail"].iter() {
16201            if self._additional_params.contains_key(field) {
16202                dlg.finished(false);
16203                return Err(common::Error::FieldClash(field));
16204            }
16205        }
16206
16207        let mut params = Params::with_capacity(3 + self._additional_params.len());
16208        params.push("userId", self._user_id);
16209        params.push("delegateEmail", self._delegate_email);
16210
16211        params.extend(self._additional_params.iter());
16212
16213        let mut url = self.hub._base_url.clone()
16214            + "gmail/v1/users/{userId}/settings/delegates/{delegateEmail}";
16215        if self._scopes.is_empty() {
16216            self._scopes
16217                .insert(Scope::SettingSharing.as_ref().to_string());
16218        }
16219
16220        #[allow(clippy::single_element_loop)]
16221        for &(find_this, param_name) in
16222            [("{userId}", "userId"), ("{delegateEmail}", "delegateEmail")].iter()
16223        {
16224            url = params.uri_replacement(url, param_name, find_this, false);
16225        }
16226        {
16227            let to_remove = ["delegateEmail", "userId"];
16228            params.remove_params(&to_remove);
16229        }
16230
16231        let url = params.parse_with_url(&url);
16232
16233        loop {
16234            let token = match self
16235                .hub
16236                .auth
16237                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
16238                .await
16239            {
16240                Ok(token) => token,
16241                Err(e) => match dlg.token(e) {
16242                    Ok(token) => token,
16243                    Err(e) => {
16244                        dlg.finished(false);
16245                        return Err(common::Error::MissingToken(e));
16246                    }
16247                },
16248            };
16249            let mut req_result = {
16250                let client = &self.hub.client;
16251                dlg.pre_request();
16252                let mut req_builder = hyper::Request::builder()
16253                    .method(hyper::Method::DELETE)
16254                    .uri(url.as_str())
16255                    .header(USER_AGENT, self.hub._user_agent.clone());
16256
16257                if let Some(token) = token.as_ref() {
16258                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
16259                }
16260
16261                let request = req_builder
16262                    .header(CONTENT_LENGTH, 0_u64)
16263                    .body(common::to_body::<String>(None));
16264
16265                client.request(request.unwrap()).await
16266            };
16267
16268            match req_result {
16269                Err(err) => {
16270                    if let common::Retry::After(d) = dlg.http_error(&err) {
16271                        sleep(d).await;
16272                        continue;
16273                    }
16274                    dlg.finished(false);
16275                    return Err(common::Error::HttpError(err));
16276                }
16277                Ok(res) => {
16278                    let (mut parts, body) = res.into_parts();
16279                    let mut body = common::Body::new(body);
16280                    if !parts.status.is_success() {
16281                        let bytes = common::to_bytes(body).await.unwrap_or_default();
16282                        let error = serde_json::from_str(&common::to_string(&bytes));
16283                        let response = common::to_response(parts, bytes.into());
16284
16285                        if let common::Retry::After(d) =
16286                            dlg.http_failure(&response, error.as_ref().ok())
16287                        {
16288                            sleep(d).await;
16289                            continue;
16290                        }
16291
16292                        dlg.finished(false);
16293
16294                        return Err(match error {
16295                            Ok(value) => common::Error::BadRequest(value),
16296                            _ => common::Error::Failure(response),
16297                        });
16298                    }
16299                    let response = common::Response::from_parts(parts, body);
16300
16301                    dlg.finished(true);
16302                    return Ok(response);
16303                }
16304            }
16305        }
16306    }
16307
16308    /// User's email address. The special value "me" can be used to indicate the authenticated user.
16309    ///
16310    /// Sets the *user id* path property to the given value.
16311    ///
16312    /// Even though the property as already been set when instantiating this call,
16313    /// we provide this method for API completeness.
16314    pub fn user_id(mut self, new_value: &str) -> UserSettingDelegateDeleteCall<'a, C> {
16315        self._user_id = new_value.to_string();
16316        self
16317    }
16318    /// The email address of the user to be removed as a delegate.
16319    ///
16320    /// Sets the *delegate email* path property to the given value.
16321    ///
16322    /// Even though the property as already been set when instantiating this call,
16323    /// we provide this method for API completeness.
16324    pub fn delegate_email(mut self, new_value: &str) -> UserSettingDelegateDeleteCall<'a, C> {
16325        self._delegate_email = new_value.to_string();
16326        self
16327    }
16328    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
16329    /// while executing the actual API request.
16330    ///
16331    /// ````text
16332    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
16333    /// ````
16334    ///
16335    /// Sets the *delegate* property to the given value.
16336    pub fn delegate(
16337        mut self,
16338        new_value: &'a mut dyn common::Delegate,
16339    ) -> UserSettingDelegateDeleteCall<'a, C> {
16340        self._delegate = Some(new_value);
16341        self
16342    }
16343
16344    /// Set any additional parameter of the query string used in the request.
16345    /// It should be used to set parameters which are not yet available through their own
16346    /// setters.
16347    ///
16348    /// Please note that this method must not be used to set any of the known parameters
16349    /// which have their own setter method. If done anyway, the request will fail.
16350    ///
16351    /// # Additional Parameters
16352    ///
16353    /// * *$.xgafv* (query-string) - V1 error format.
16354    /// * *access_token* (query-string) - OAuth access token.
16355    /// * *alt* (query-string) - Data format for response.
16356    /// * *callback* (query-string) - JSONP
16357    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
16358    /// * *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.
16359    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
16360    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
16361    /// * *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.
16362    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
16363    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
16364    pub fn param<T>(mut self, name: T, value: T) -> UserSettingDelegateDeleteCall<'a, C>
16365    where
16366        T: AsRef<str>,
16367    {
16368        self._additional_params
16369            .insert(name.as_ref().to_string(), value.as_ref().to_string());
16370        self
16371    }
16372
16373    /// Identifies the authorization scope for the method you are building.
16374    ///
16375    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
16376    /// [`Scope::SettingSharing`].
16377    ///
16378    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
16379    /// tokens for more than one scope.
16380    ///
16381    /// Usually there is more than one suitable scope to authorize an operation, some of which may
16382    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
16383    /// sufficient, a read-write scope will do as well.
16384    pub fn add_scope<St>(mut self, scope: St) -> UserSettingDelegateDeleteCall<'a, C>
16385    where
16386        St: AsRef<str>,
16387    {
16388        self._scopes.insert(String::from(scope.as_ref()));
16389        self
16390    }
16391    /// Identifies the authorization scope(s) for the method you are building.
16392    ///
16393    /// See [`Self::add_scope()`] for details.
16394    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingDelegateDeleteCall<'a, C>
16395    where
16396        I: IntoIterator<Item = St>,
16397        St: AsRef<str>,
16398    {
16399        self._scopes
16400            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
16401        self
16402    }
16403
16404    /// Removes all scopes, and no default scope will be used either.
16405    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
16406    /// for details).
16407    pub fn clear_scopes(mut self) -> UserSettingDelegateDeleteCall<'a, C> {
16408        self._scopes.clear();
16409        self
16410    }
16411}
16412
16413/// Gets the specified delegate. Note that a delegate user must be referred to by their primary email address, and not an email alias. This method is only available to service account clients that have been delegated domain-wide authority.
16414///
16415/// A builder for the *settings.delegates.get* method supported by a *user* resource.
16416/// It is not used directly, but through a [`UserMethods`] instance.
16417///
16418/// # Example
16419///
16420/// Instantiate a resource method builder
16421///
16422/// ```test_harness,no_run
16423/// # extern crate hyper;
16424/// # extern crate hyper_rustls;
16425/// # extern crate google_gmail1 as gmail1;
16426/// # async fn dox() {
16427/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
16428///
16429/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
16430/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
16431/// #     secret,
16432/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
16433/// # ).build().await.unwrap();
16434///
16435/// # let client = hyper_util::client::legacy::Client::builder(
16436/// #     hyper_util::rt::TokioExecutor::new()
16437/// # )
16438/// # .build(
16439/// #     hyper_rustls::HttpsConnectorBuilder::new()
16440/// #         .with_native_roots()
16441/// #         .unwrap()
16442/// #         .https_or_http()
16443/// #         .enable_http1()
16444/// #         .build()
16445/// # );
16446/// # let mut hub = Gmail::new(client, auth);
16447/// // You can configure optional parameters by calling the respective setters at will, and
16448/// // execute the final call using `doit()`.
16449/// // Values shown here are possibly random and not representative !
16450/// let result = hub.users().settings_delegates_get("userId", "delegateEmail")
16451///              .doit().await;
16452/// # }
16453/// ```
16454pub struct UserSettingDelegateGetCall<'a, C>
16455where
16456    C: 'a,
16457{
16458    hub: &'a Gmail<C>,
16459    _user_id: String,
16460    _delegate_email: String,
16461    _delegate: Option<&'a mut dyn common::Delegate>,
16462    _additional_params: HashMap<String, String>,
16463    _scopes: BTreeSet<String>,
16464}
16465
16466impl<'a, C> common::CallBuilder for UserSettingDelegateGetCall<'a, C> {}
16467
16468impl<'a, C> UserSettingDelegateGetCall<'a, C>
16469where
16470    C: common::Connector,
16471{
16472    /// Perform the operation you have build so far.
16473    pub async fn doit(mut self) -> common::Result<(common::Response, Delegate)> {
16474        use std::borrow::Cow;
16475        use std::io::{Read, Seek};
16476
16477        use common::{url::Params, ToParts};
16478        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
16479
16480        let mut dd = common::DefaultDelegate;
16481        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
16482        dlg.begin(common::MethodInfo {
16483            id: "gmail.users.settings.delegates.get",
16484            http_method: hyper::Method::GET,
16485        });
16486
16487        for &field in ["alt", "userId", "delegateEmail"].iter() {
16488            if self._additional_params.contains_key(field) {
16489                dlg.finished(false);
16490                return Err(common::Error::FieldClash(field));
16491            }
16492        }
16493
16494        let mut params = Params::with_capacity(4 + self._additional_params.len());
16495        params.push("userId", self._user_id);
16496        params.push("delegateEmail", self._delegate_email);
16497
16498        params.extend(self._additional_params.iter());
16499
16500        params.push("alt", "json");
16501        let mut url = self.hub._base_url.clone()
16502            + "gmail/v1/users/{userId}/settings/delegates/{delegateEmail}";
16503        if self._scopes.is_empty() {
16504            self._scopes.insert(Scope::Readonly.as_ref().to_string());
16505        }
16506
16507        #[allow(clippy::single_element_loop)]
16508        for &(find_this, param_name) in
16509            [("{userId}", "userId"), ("{delegateEmail}", "delegateEmail")].iter()
16510        {
16511            url = params.uri_replacement(url, param_name, find_this, false);
16512        }
16513        {
16514            let to_remove = ["delegateEmail", "userId"];
16515            params.remove_params(&to_remove);
16516        }
16517
16518        let url = params.parse_with_url(&url);
16519
16520        loop {
16521            let token = match self
16522                .hub
16523                .auth
16524                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
16525                .await
16526            {
16527                Ok(token) => token,
16528                Err(e) => match dlg.token(e) {
16529                    Ok(token) => token,
16530                    Err(e) => {
16531                        dlg.finished(false);
16532                        return Err(common::Error::MissingToken(e));
16533                    }
16534                },
16535            };
16536            let mut req_result = {
16537                let client = &self.hub.client;
16538                dlg.pre_request();
16539                let mut req_builder = hyper::Request::builder()
16540                    .method(hyper::Method::GET)
16541                    .uri(url.as_str())
16542                    .header(USER_AGENT, self.hub._user_agent.clone());
16543
16544                if let Some(token) = token.as_ref() {
16545                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
16546                }
16547
16548                let request = req_builder
16549                    .header(CONTENT_LENGTH, 0_u64)
16550                    .body(common::to_body::<String>(None));
16551
16552                client.request(request.unwrap()).await
16553            };
16554
16555            match req_result {
16556                Err(err) => {
16557                    if let common::Retry::After(d) = dlg.http_error(&err) {
16558                        sleep(d).await;
16559                        continue;
16560                    }
16561                    dlg.finished(false);
16562                    return Err(common::Error::HttpError(err));
16563                }
16564                Ok(res) => {
16565                    let (mut parts, body) = res.into_parts();
16566                    let mut body = common::Body::new(body);
16567                    if !parts.status.is_success() {
16568                        let bytes = common::to_bytes(body).await.unwrap_or_default();
16569                        let error = serde_json::from_str(&common::to_string(&bytes));
16570                        let response = common::to_response(parts, bytes.into());
16571
16572                        if let common::Retry::After(d) =
16573                            dlg.http_failure(&response, error.as_ref().ok())
16574                        {
16575                            sleep(d).await;
16576                            continue;
16577                        }
16578
16579                        dlg.finished(false);
16580
16581                        return Err(match error {
16582                            Ok(value) => common::Error::BadRequest(value),
16583                            _ => common::Error::Failure(response),
16584                        });
16585                    }
16586                    let response = {
16587                        let bytes = common::to_bytes(body).await.unwrap_or_default();
16588                        let encoded = common::to_string(&bytes);
16589                        match serde_json::from_str(&encoded) {
16590                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
16591                            Err(error) => {
16592                                dlg.response_json_decode_error(&encoded, &error);
16593                                return Err(common::Error::JsonDecodeError(
16594                                    encoded.to_string(),
16595                                    error,
16596                                ));
16597                            }
16598                        }
16599                    };
16600
16601                    dlg.finished(true);
16602                    return Ok(response);
16603                }
16604            }
16605        }
16606    }
16607
16608    /// User's email address. The special value "me" can be used to indicate the authenticated user.
16609    ///
16610    /// Sets the *user id* path property to the given value.
16611    ///
16612    /// Even though the property as already been set when instantiating this call,
16613    /// we provide this method for API completeness.
16614    pub fn user_id(mut self, new_value: &str) -> UserSettingDelegateGetCall<'a, C> {
16615        self._user_id = new_value.to_string();
16616        self
16617    }
16618    /// The email address of the user whose delegate relationship is to be retrieved.
16619    ///
16620    /// Sets the *delegate email* path property to the given value.
16621    ///
16622    /// Even though the property as already been set when instantiating this call,
16623    /// we provide this method for API completeness.
16624    pub fn delegate_email(mut self, new_value: &str) -> UserSettingDelegateGetCall<'a, C> {
16625        self._delegate_email = new_value.to_string();
16626        self
16627    }
16628    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
16629    /// while executing the actual API request.
16630    ///
16631    /// ````text
16632    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
16633    /// ````
16634    ///
16635    /// Sets the *delegate* property to the given value.
16636    pub fn delegate(
16637        mut self,
16638        new_value: &'a mut dyn common::Delegate,
16639    ) -> UserSettingDelegateGetCall<'a, C> {
16640        self._delegate = Some(new_value);
16641        self
16642    }
16643
16644    /// Set any additional parameter of the query string used in the request.
16645    /// It should be used to set parameters which are not yet available through their own
16646    /// setters.
16647    ///
16648    /// Please note that this method must not be used to set any of the known parameters
16649    /// which have their own setter method. If done anyway, the request will fail.
16650    ///
16651    /// # Additional Parameters
16652    ///
16653    /// * *$.xgafv* (query-string) - V1 error format.
16654    /// * *access_token* (query-string) - OAuth access token.
16655    /// * *alt* (query-string) - Data format for response.
16656    /// * *callback* (query-string) - JSONP
16657    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
16658    /// * *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.
16659    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
16660    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
16661    /// * *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.
16662    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
16663    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
16664    pub fn param<T>(mut self, name: T, value: T) -> UserSettingDelegateGetCall<'a, C>
16665    where
16666        T: AsRef<str>,
16667    {
16668        self._additional_params
16669            .insert(name.as_ref().to_string(), value.as_ref().to_string());
16670        self
16671    }
16672
16673    /// Identifies the authorization scope for the method you are building.
16674    ///
16675    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
16676    /// [`Scope::Readonly`].
16677    ///
16678    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
16679    /// tokens for more than one scope.
16680    ///
16681    /// Usually there is more than one suitable scope to authorize an operation, some of which may
16682    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
16683    /// sufficient, a read-write scope will do as well.
16684    pub fn add_scope<St>(mut self, scope: St) -> UserSettingDelegateGetCall<'a, C>
16685    where
16686        St: AsRef<str>,
16687    {
16688        self._scopes.insert(String::from(scope.as_ref()));
16689        self
16690    }
16691    /// Identifies the authorization scope(s) for the method you are building.
16692    ///
16693    /// See [`Self::add_scope()`] for details.
16694    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingDelegateGetCall<'a, C>
16695    where
16696        I: IntoIterator<Item = St>,
16697        St: AsRef<str>,
16698    {
16699        self._scopes
16700            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
16701        self
16702    }
16703
16704    /// Removes all scopes, and no default scope will be used either.
16705    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
16706    /// for details).
16707    pub fn clear_scopes(mut self) -> UserSettingDelegateGetCall<'a, C> {
16708        self._scopes.clear();
16709        self
16710    }
16711}
16712
16713/// Lists the delegates for the specified account. This method is only available to service account clients that have been delegated domain-wide authority.
16714///
16715/// A builder for the *settings.delegates.list* method supported by a *user* resource.
16716/// It is not used directly, but through a [`UserMethods`] instance.
16717///
16718/// # Example
16719///
16720/// Instantiate a resource method builder
16721///
16722/// ```test_harness,no_run
16723/// # extern crate hyper;
16724/// # extern crate hyper_rustls;
16725/// # extern crate google_gmail1 as gmail1;
16726/// # async fn dox() {
16727/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
16728///
16729/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
16730/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
16731/// #     secret,
16732/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
16733/// # ).build().await.unwrap();
16734///
16735/// # let client = hyper_util::client::legacy::Client::builder(
16736/// #     hyper_util::rt::TokioExecutor::new()
16737/// # )
16738/// # .build(
16739/// #     hyper_rustls::HttpsConnectorBuilder::new()
16740/// #         .with_native_roots()
16741/// #         .unwrap()
16742/// #         .https_or_http()
16743/// #         .enable_http1()
16744/// #         .build()
16745/// # );
16746/// # let mut hub = Gmail::new(client, auth);
16747/// // You can configure optional parameters by calling the respective setters at will, and
16748/// // execute the final call using `doit()`.
16749/// // Values shown here are possibly random and not representative !
16750/// let result = hub.users().settings_delegates_list("userId")
16751///              .doit().await;
16752/// # }
16753/// ```
16754pub struct UserSettingDelegateListCall<'a, C>
16755where
16756    C: 'a,
16757{
16758    hub: &'a Gmail<C>,
16759    _user_id: String,
16760    _delegate: Option<&'a mut dyn common::Delegate>,
16761    _additional_params: HashMap<String, String>,
16762    _scopes: BTreeSet<String>,
16763}
16764
16765impl<'a, C> common::CallBuilder for UserSettingDelegateListCall<'a, C> {}
16766
16767impl<'a, C> UserSettingDelegateListCall<'a, C>
16768where
16769    C: common::Connector,
16770{
16771    /// Perform the operation you have build so far.
16772    pub async fn doit(mut self) -> common::Result<(common::Response, ListDelegatesResponse)> {
16773        use std::borrow::Cow;
16774        use std::io::{Read, Seek};
16775
16776        use common::{url::Params, ToParts};
16777        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
16778
16779        let mut dd = common::DefaultDelegate;
16780        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
16781        dlg.begin(common::MethodInfo {
16782            id: "gmail.users.settings.delegates.list",
16783            http_method: hyper::Method::GET,
16784        });
16785
16786        for &field in ["alt", "userId"].iter() {
16787            if self._additional_params.contains_key(field) {
16788                dlg.finished(false);
16789                return Err(common::Error::FieldClash(field));
16790            }
16791        }
16792
16793        let mut params = Params::with_capacity(3 + self._additional_params.len());
16794        params.push("userId", self._user_id);
16795
16796        params.extend(self._additional_params.iter());
16797
16798        params.push("alt", "json");
16799        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/delegates";
16800        if self._scopes.is_empty() {
16801            self._scopes.insert(Scope::Readonly.as_ref().to_string());
16802        }
16803
16804        #[allow(clippy::single_element_loop)]
16805        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
16806            url = params.uri_replacement(url, param_name, find_this, false);
16807        }
16808        {
16809            let to_remove = ["userId"];
16810            params.remove_params(&to_remove);
16811        }
16812
16813        let url = params.parse_with_url(&url);
16814
16815        loop {
16816            let token = match self
16817                .hub
16818                .auth
16819                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
16820                .await
16821            {
16822                Ok(token) => token,
16823                Err(e) => match dlg.token(e) {
16824                    Ok(token) => token,
16825                    Err(e) => {
16826                        dlg.finished(false);
16827                        return Err(common::Error::MissingToken(e));
16828                    }
16829                },
16830            };
16831            let mut req_result = {
16832                let client = &self.hub.client;
16833                dlg.pre_request();
16834                let mut req_builder = hyper::Request::builder()
16835                    .method(hyper::Method::GET)
16836                    .uri(url.as_str())
16837                    .header(USER_AGENT, self.hub._user_agent.clone());
16838
16839                if let Some(token) = token.as_ref() {
16840                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
16841                }
16842
16843                let request = req_builder
16844                    .header(CONTENT_LENGTH, 0_u64)
16845                    .body(common::to_body::<String>(None));
16846
16847                client.request(request.unwrap()).await
16848            };
16849
16850            match req_result {
16851                Err(err) => {
16852                    if let common::Retry::After(d) = dlg.http_error(&err) {
16853                        sleep(d).await;
16854                        continue;
16855                    }
16856                    dlg.finished(false);
16857                    return Err(common::Error::HttpError(err));
16858                }
16859                Ok(res) => {
16860                    let (mut parts, body) = res.into_parts();
16861                    let mut body = common::Body::new(body);
16862                    if !parts.status.is_success() {
16863                        let bytes = common::to_bytes(body).await.unwrap_or_default();
16864                        let error = serde_json::from_str(&common::to_string(&bytes));
16865                        let response = common::to_response(parts, bytes.into());
16866
16867                        if let common::Retry::After(d) =
16868                            dlg.http_failure(&response, error.as_ref().ok())
16869                        {
16870                            sleep(d).await;
16871                            continue;
16872                        }
16873
16874                        dlg.finished(false);
16875
16876                        return Err(match error {
16877                            Ok(value) => common::Error::BadRequest(value),
16878                            _ => common::Error::Failure(response),
16879                        });
16880                    }
16881                    let response = {
16882                        let bytes = common::to_bytes(body).await.unwrap_or_default();
16883                        let encoded = common::to_string(&bytes);
16884                        match serde_json::from_str(&encoded) {
16885                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
16886                            Err(error) => {
16887                                dlg.response_json_decode_error(&encoded, &error);
16888                                return Err(common::Error::JsonDecodeError(
16889                                    encoded.to_string(),
16890                                    error,
16891                                ));
16892                            }
16893                        }
16894                    };
16895
16896                    dlg.finished(true);
16897                    return Ok(response);
16898                }
16899            }
16900        }
16901    }
16902
16903    /// User's email address. The special value "me" can be used to indicate the authenticated user.
16904    ///
16905    /// Sets the *user id* path property to the given value.
16906    ///
16907    /// Even though the property as already been set when instantiating this call,
16908    /// we provide this method for API completeness.
16909    pub fn user_id(mut self, new_value: &str) -> UserSettingDelegateListCall<'a, C> {
16910        self._user_id = new_value.to_string();
16911        self
16912    }
16913    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
16914    /// while executing the actual API request.
16915    ///
16916    /// ````text
16917    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
16918    /// ````
16919    ///
16920    /// Sets the *delegate* property to the given value.
16921    pub fn delegate(
16922        mut self,
16923        new_value: &'a mut dyn common::Delegate,
16924    ) -> UserSettingDelegateListCall<'a, C> {
16925        self._delegate = Some(new_value);
16926        self
16927    }
16928
16929    /// Set any additional parameter of the query string used in the request.
16930    /// It should be used to set parameters which are not yet available through their own
16931    /// setters.
16932    ///
16933    /// Please note that this method must not be used to set any of the known parameters
16934    /// which have their own setter method. If done anyway, the request will fail.
16935    ///
16936    /// # Additional Parameters
16937    ///
16938    /// * *$.xgafv* (query-string) - V1 error format.
16939    /// * *access_token* (query-string) - OAuth access token.
16940    /// * *alt* (query-string) - Data format for response.
16941    /// * *callback* (query-string) - JSONP
16942    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
16943    /// * *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.
16944    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
16945    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
16946    /// * *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.
16947    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
16948    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
16949    pub fn param<T>(mut self, name: T, value: T) -> UserSettingDelegateListCall<'a, C>
16950    where
16951        T: AsRef<str>,
16952    {
16953        self._additional_params
16954            .insert(name.as_ref().to_string(), value.as_ref().to_string());
16955        self
16956    }
16957
16958    /// Identifies the authorization scope for the method you are building.
16959    ///
16960    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
16961    /// [`Scope::Readonly`].
16962    ///
16963    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
16964    /// tokens for more than one scope.
16965    ///
16966    /// Usually there is more than one suitable scope to authorize an operation, some of which may
16967    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
16968    /// sufficient, a read-write scope will do as well.
16969    pub fn add_scope<St>(mut self, scope: St) -> UserSettingDelegateListCall<'a, C>
16970    where
16971        St: AsRef<str>,
16972    {
16973        self._scopes.insert(String::from(scope.as_ref()));
16974        self
16975    }
16976    /// Identifies the authorization scope(s) for the method you are building.
16977    ///
16978    /// See [`Self::add_scope()`] for details.
16979    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingDelegateListCall<'a, C>
16980    where
16981        I: IntoIterator<Item = St>,
16982        St: AsRef<str>,
16983    {
16984        self._scopes
16985            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
16986        self
16987    }
16988
16989    /// Removes all scopes, and no default scope will be used either.
16990    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
16991    /// for details).
16992    pub fn clear_scopes(mut self) -> UserSettingDelegateListCall<'a, C> {
16993        self._scopes.clear();
16994        self
16995    }
16996}
16997
16998/// Creates a filter. Note: you can only create a maximum of 1,000 filters.
16999///
17000/// A builder for the *settings.filters.create* method supported by a *user* resource.
17001/// It is not used directly, but through a [`UserMethods`] instance.
17002///
17003/// # Example
17004///
17005/// Instantiate a resource method builder
17006///
17007/// ```test_harness,no_run
17008/// # extern crate hyper;
17009/// # extern crate hyper_rustls;
17010/// # extern crate google_gmail1 as gmail1;
17011/// use gmail1::api::Filter;
17012/// # async fn dox() {
17013/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
17014///
17015/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
17016/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
17017/// #     secret,
17018/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
17019/// # ).build().await.unwrap();
17020///
17021/// # let client = hyper_util::client::legacy::Client::builder(
17022/// #     hyper_util::rt::TokioExecutor::new()
17023/// # )
17024/// # .build(
17025/// #     hyper_rustls::HttpsConnectorBuilder::new()
17026/// #         .with_native_roots()
17027/// #         .unwrap()
17028/// #         .https_or_http()
17029/// #         .enable_http1()
17030/// #         .build()
17031/// # );
17032/// # let mut hub = Gmail::new(client, auth);
17033/// // As the method needs a request, you would usually fill it with the desired information
17034/// // into the respective structure. Some of the parts shown here might not be applicable !
17035/// // Values shown here are possibly random and not representative !
17036/// let mut req = Filter::default();
17037///
17038/// // You can configure optional parameters by calling the respective setters at will, and
17039/// // execute the final call using `doit()`.
17040/// // Values shown here are possibly random and not representative !
17041/// let result = hub.users().settings_filters_create(req, "userId")
17042///              .doit().await;
17043/// # }
17044/// ```
17045pub struct UserSettingFilterCreateCall<'a, C>
17046where
17047    C: 'a,
17048{
17049    hub: &'a Gmail<C>,
17050    _request: Filter,
17051    _user_id: String,
17052    _delegate: Option<&'a mut dyn common::Delegate>,
17053    _additional_params: HashMap<String, String>,
17054    _scopes: BTreeSet<String>,
17055}
17056
17057impl<'a, C> common::CallBuilder for UserSettingFilterCreateCall<'a, C> {}
17058
17059impl<'a, C> UserSettingFilterCreateCall<'a, C>
17060where
17061    C: common::Connector,
17062{
17063    /// Perform the operation you have build so far.
17064    pub async fn doit(mut self) -> common::Result<(common::Response, Filter)> {
17065        use std::borrow::Cow;
17066        use std::io::{Read, Seek};
17067
17068        use common::{url::Params, ToParts};
17069        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
17070
17071        let mut dd = common::DefaultDelegate;
17072        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
17073        dlg.begin(common::MethodInfo {
17074            id: "gmail.users.settings.filters.create",
17075            http_method: hyper::Method::POST,
17076        });
17077
17078        for &field in ["alt", "userId"].iter() {
17079            if self._additional_params.contains_key(field) {
17080                dlg.finished(false);
17081                return Err(common::Error::FieldClash(field));
17082            }
17083        }
17084
17085        let mut params = Params::with_capacity(4 + self._additional_params.len());
17086        params.push("userId", self._user_id);
17087
17088        params.extend(self._additional_params.iter());
17089
17090        params.push("alt", "json");
17091        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/filters";
17092        if self._scopes.is_empty() {
17093            self._scopes
17094                .insert(Scope::SettingBasic.as_ref().to_string());
17095        }
17096
17097        #[allow(clippy::single_element_loop)]
17098        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
17099            url = params.uri_replacement(url, param_name, find_this, false);
17100        }
17101        {
17102            let to_remove = ["userId"];
17103            params.remove_params(&to_remove);
17104        }
17105
17106        let url = params.parse_with_url(&url);
17107
17108        let mut json_mime_type = mime::APPLICATION_JSON;
17109        let mut request_value_reader = {
17110            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
17111            common::remove_json_null_values(&mut value);
17112            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
17113            serde_json::to_writer(&mut dst, &value).unwrap();
17114            dst
17115        };
17116        let request_size = request_value_reader
17117            .seek(std::io::SeekFrom::End(0))
17118            .unwrap();
17119        request_value_reader
17120            .seek(std::io::SeekFrom::Start(0))
17121            .unwrap();
17122
17123        loop {
17124            let token = match self
17125                .hub
17126                .auth
17127                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
17128                .await
17129            {
17130                Ok(token) => token,
17131                Err(e) => match dlg.token(e) {
17132                    Ok(token) => token,
17133                    Err(e) => {
17134                        dlg.finished(false);
17135                        return Err(common::Error::MissingToken(e));
17136                    }
17137                },
17138            };
17139            request_value_reader
17140                .seek(std::io::SeekFrom::Start(0))
17141                .unwrap();
17142            let mut req_result = {
17143                let client = &self.hub.client;
17144                dlg.pre_request();
17145                let mut req_builder = hyper::Request::builder()
17146                    .method(hyper::Method::POST)
17147                    .uri(url.as_str())
17148                    .header(USER_AGENT, self.hub._user_agent.clone());
17149
17150                if let Some(token) = token.as_ref() {
17151                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
17152                }
17153
17154                let request = req_builder
17155                    .header(CONTENT_TYPE, json_mime_type.to_string())
17156                    .header(CONTENT_LENGTH, request_size as u64)
17157                    .body(common::to_body(
17158                        request_value_reader.get_ref().clone().into(),
17159                    ));
17160
17161                client.request(request.unwrap()).await
17162            };
17163
17164            match req_result {
17165                Err(err) => {
17166                    if let common::Retry::After(d) = dlg.http_error(&err) {
17167                        sleep(d).await;
17168                        continue;
17169                    }
17170                    dlg.finished(false);
17171                    return Err(common::Error::HttpError(err));
17172                }
17173                Ok(res) => {
17174                    let (mut parts, body) = res.into_parts();
17175                    let mut body = common::Body::new(body);
17176                    if !parts.status.is_success() {
17177                        let bytes = common::to_bytes(body).await.unwrap_or_default();
17178                        let error = serde_json::from_str(&common::to_string(&bytes));
17179                        let response = common::to_response(parts, bytes.into());
17180
17181                        if let common::Retry::After(d) =
17182                            dlg.http_failure(&response, error.as_ref().ok())
17183                        {
17184                            sleep(d).await;
17185                            continue;
17186                        }
17187
17188                        dlg.finished(false);
17189
17190                        return Err(match error {
17191                            Ok(value) => common::Error::BadRequest(value),
17192                            _ => common::Error::Failure(response),
17193                        });
17194                    }
17195                    let response = {
17196                        let bytes = common::to_bytes(body).await.unwrap_or_default();
17197                        let encoded = common::to_string(&bytes);
17198                        match serde_json::from_str(&encoded) {
17199                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
17200                            Err(error) => {
17201                                dlg.response_json_decode_error(&encoded, &error);
17202                                return Err(common::Error::JsonDecodeError(
17203                                    encoded.to_string(),
17204                                    error,
17205                                ));
17206                            }
17207                        }
17208                    };
17209
17210                    dlg.finished(true);
17211                    return Ok(response);
17212                }
17213            }
17214        }
17215    }
17216
17217    ///
17218    /// Sets the *request* property to the given value.
17219    ///
17220    /// Even though the property as already been set when instantiating this call,
17221    /// we provide this method for API completeness.
17222    pub fn request(mut self, new_value: Filter) -> UserSettingFilterCreateCall<'a, C> {
17223        self._request = new_value;
17224        self
17225    }
17226    /// User's email address. The special value "me" can be used to indicate the authenticated user.
17227    ///
17228    /// Sets the *user id* path property to the given value.
17229    ///
17230    /// Even though the property as already been set when instantiating this call,
17231    /// we provide this method for API completeness.
17232    pub fn user_id(mut self, new_value: &str) -> UserSettingFilterCreateCall<'a, C> {
17233        self._user_id = new_value.to_string();
17234        self
17235    }
17236    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
17237    /// while executing the actual API request.
17238    ///
17239    /// ````text
17240    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
17241    /// ````
17242    ///
17243    /// Sets the *delegate* property to the given value.
17244    pub fn delegate(
17245        mut self,
17246        new_value: &'a mut dyn common::Delegate,
17247    ) -> UserSettingFilterCreateCall<'a, C> {
17248        self._delegate = Some(new_value);
17249        self
17250    }
17251
17252    /// Set any additional parameter of the query string used in the request.
17253    /// It should be used to set parameters which are not yet available through their own
17254    /// setters.
17255    ///
17256    /// Please note that this method must not be used to set any of the known parameters
17257    /// which have their own setter method. If done anyway, the request will fail.
17258    ///
17259    /// # Additional Parameters
17260    ///
17261    /// * *$.xgafv* (query-string) - V1 error format.
17262    /// * *access_token* (query-string) - OAuth access token.
17263    /// * *alt* (query-string) - Data format for response.
17264    /// * *callback* (query-string) - JSONP
17265    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
17266    /// * *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.
17267    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
17268    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
17269    /// * *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.
17270    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
17271    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
17272    pub fn param<T>(mut self, name: T, value: T) -> UserSettingFilterCreateCall<'a, C>
17273    where
17274        T: AsRef<str>,
17275    {
17276        self._additional_params
17277            .insert(name.as_ref().to_string(), value.as_ref().to_string());
17278        self
17279    }
17280
17281    /// Identifies the authorization scope for the method you are building.
17282    ///
17283    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
17284    /// [`Scope::SettingBasic`].
17285    ///
17286    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
17287    /// tokens for more than one scope.
17288    ///
17289    /// Usually there is more than one suitable scope to authorize an operation, some of which may
17290    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
17291    /// sufficient, a read-write scope will do as well.
17292    pub fn add_scope<St>(mut self, scope: St) -> UserSettingFilterCreateCall<'a, C>
17293    where
17294        St: AsRef<str>,
17295    {
17296        self._scopes.insert(String::from(scope.as_ref()));
17297        self
17298    }
17299    /// Identifies the authorization scope(s) for the method you are building.
17300    ///
17301    /// See [`Self::add_scope()`] for details.
17302    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingFilterCreateCall<'a, C>
17303    where
17304        I: IntoIterator<Item = St>,
17305        St: AsRef<str>,
17306    {
17307        self._scopes
17308            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
17309        self
17310    }
17311
17312    /// Removes all scopes, and no default scope will be used either.
17313    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
17314    /// for details).
17315    pub fn clear_scopes(mut self) -> UserSettingFilterCreateCall<'a, C> {
17316        self._scopes.clear();
17317        self
17318    }
17319}
17320
17321/// Immediately and permanently deletes the specified filter.
17322///
17323/// A builder for the *settings.filters.delete* method supported by a *user* resource.
17324/// It is not used directly, but through a [`UserMethods`] instance.
17325///
17326/// # Example
17327///
17328/// Instantiate a resource method builder
17329///
17330/// ```test_harness,no_run
17331/// # extern crate hyper;
17332/// # extern crate hyper_rustls;
17333/// # extern crate google_gmail1 as gmail1;
17334/// # async fn dox() {
17335/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
17336///
17337/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
17338/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
17339/// #     secret,
17340/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
17341/// # ).build().await.unwrap();
17342///
17343/// # let client = hyper_util::client::legacy::Client::builder(
17344/// #     hyper_util::rt::TokioExecutor::new()
17345/// # )
17346/// # .build(
17347/// #     hyper_rustls::HttpsConnectorBuilder::new()
17348/// #         .with_native_roots()
17349/// #         .unwrap()
17350/// #         .https_or_http()
17351/// #         .enable_http1()
17352/// #         .build()
17353/// # );
17354/// # let mut hub = Gmail::new(client, auth);
17355/// // You can configure optional parameters by calling the respective setters at will, and
17356/// // execute the final call using `doit()`.
17357/// // Values shown here are possibly random and not representative !
17358/// let result = hub.users().settings_filters_delete("userId", "id")
17359///              .doit().await;
17360/// # }
17361/// ```
17362pub struct UserSettingFilterDeleteCall<'a, C>
17363where
17364    C: 'a,
17365{
17366    hub: &'a Gmail<C>,
17367    _user_id: String,
17368    _id: String,
17369    _delegate: Option<&'a mut dyn common::Delegate>,
17370    _additional_params: HashMap<String, String>,
17371    _scopes: BTreeSet<String>,
17372}
17373
17374impl<'a, C> common::CallBuilder for UserSettingFilterDeleteCall<'a, C> {}
17375
17376impl<'a, C> UserSettingFilterDeleteCall<'a, C>
17377where
17378    C: common::Connector,
17379{
17380    /// Perform the operation you have build so far.
17381    pub async fn doit(mut self) -> common::Result<common::Response> {
17382        use std::borrow::Cow;
17383        use std::io::{Read, Seek};
17384
17385        use common::{url::Params, ToParts};
17386        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
17387
17388        let mut dd = common::DefaultDelegate;
17389        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
17390        dlg.begin(common::MethodInfo {
17391            id: "gmail.users.settings.filters.delete",
17392            http_method: hyper::Method::DELETE,
17393        });
17394
17395        for &field in ["userId", "id"].iter() {
17396            if self._additional_params.contains_key(field) {
17397                dlg.finished(false);
17398                return Err(common::Error::FieldClash(field));
17399            }
17400        }
17401
17402        let mut params = Params::with_capacity(3 + self._additional_params.len());
17403        params.push("userId", self._user_id);
17404        params.push("id", self._id);
17405
17406        params.extend(self._additional_params.iter());
17407
17408        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/filters/{id}";
17409        if self._scopes.is_empty() {
17410            self._scopes
17411                .insert(Scope::SettingBasic.as_ref().to_string());
17412        }
17413
17414        #[allow(clippy::single_element_loop)]
17415        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
17416            url = params.uri_replacement(url, param_name, find_this, false);
17417        }
17418        {
17419            let to_remove = ["id", "userId"];
17420            params.remove_params(&to_remove);
17421        }
17422
17423        let url = params.parse_with_url(&url);
17424
17425        loop {
17426            let token = match self
17427                .hub
17428                .auth
17429                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
17430                .await
17431            {
17432                Ok(token) => token,
17433                Err(e) => match dlg.token(e) {
17434                    Ok(token) => token,
17435                    Err(e) => {
17436                        dlg.finished(false);
17437                        return Err(common::Error::MissingToken(e));
17438                    }
17439                },
17440            };
17441            let mut req_result = {
17442                let client = &self.hub.client;
17443                dlg.pre_request();
17444                let mut req_builder = hyper::Request::builder()
17445                    .method(hyper::Method::DELETE)
17446                    .uri(url.as_str())
17447                    .header(USER_AGENT, self.hub._user_agent.clone());
17448
17449                if let Some(token) = token.as_ref() {
17450                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
17451                }
17452
17453                let request = req_builder
17454                    .header(CONTENT_LENGTH, 0_u64)
17455                    .body(common::to_body::<String>(None));
17456
17457                client.request(request.unwrap()).await
17458            };
17459
17460            match req_result {
17461                Err(err) => {
17462                    if let common::Retry::After(d) = dlg.http_error(&err) {
17463                        sleep(d).await;
17464                        continue;
17465                    }
17466                    dlg.finished(false);
17467                    return Err(common::Error::HttpError(err));
17468                }
17469                Ok(res) => {
17470                    let (mut parts, body) = res.into_parts();
17471                    let mut body = common::Body::new(body);
17472                    if !parts.status.is_success() {
17473                        let bytes = common::to_bytes(body).await.unwrap_or_default();
17474                        let error = serde_json::from_str(&common::to_string(&bytes));
17475                        let response = common::to_response(parts, bytes.into());
17476
17477                        if let common::Retry::After(d) =
17478                            dlg.http_failure(&response, error.as_ref().ok())
17479                        {
17480                            sleep(d).await;
17481                            continue;
17482                        }
17483
17484                        dlg.finished(false);
17485
17486                        return Err(match error {
17487                            Ok(value) => common::Error::BadRequest(value),
17488                            _ => common::Error::Failure(response),
17489                        });
17490                    }
17491                    let response = common::Response::from_parts(parts, body);
17492
17493                    dlg.finished(true);
17494                    return Ok(response);
17495                }
17496            }
17497        }
17498    }
17499
17500    /// User's email address. The special value "me" can be used to indicate the authenticated user.
17501    ///
17502    /// Sets the *user id* path property to the given value.
17503    ///
17504    /// Even though the property as already been set when instantiating this call,
17505    /// we provide this method for API completeness.
17506    pub fn user_id(mut self, new_value: &str) -> UserSettingFilterDeleteCall<'a, C> {
17507        self._user_id = new_value.to_string();
17508        self
17509    }
17510    /// The ID of the filter to be deleted.
17511    ///
17512    /// Sets the *id* path property to the given value.
17513    ///
17514    /// Even though the property as already been set when instantiating this call,
17515    /// we provide this method for API completeness.
17516    pub fn id(mut self, new_value: &str) -> UserSettingFilterDeleteCall<'a, C> {
17517        self._id = new_value.to_string();
17518        self
17519    }
17520    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
17521    /// while executing the actual API request.
17522    ///
17523    /// ````text
17524    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
17525    /// ````
17526    ///
17527    /// Sets the *delegate* property to the given value.
17528    pub fn delegate(
17529        mut self,
17530        new_value: &'a mut dyn common::Delegate,
17531    ) -> UserSettingFilterDeleteCall<'a, C> {
17532        self._delegate = Some(new_value);
17533        self
17534    }
17535
17536    /// Set any additional parameter of the query string used in the request.
17537    /// It should be used to set parameters which are not yet available through their own
17538    /// setters.
17539    ///
17540    /// Please note that this method must not be used to set any of the known parameters
17541    /// which have their own setter method. If done anyway, the request will fail.
17542    ///
17543    /// # Additional Parameters
17544    ///
17545    /// * *$.xgafv* (query-string) - V1 error format.
17546    /// * *access_token* (query-string) - OAuth access token.
17547    /// * *alt* (query-string) - Data format for response.
17548    /// * *callback* (query-string) - JSONP
17549    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
17550    /// * *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.
17551    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
17552    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
17553    /// * *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.
17554    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
17555    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
17556    pub fn param<T>(mut self, name: T, value: T) -> UserSettingFilterDeleteCall<'a, C>
17557    where
17558        T: AsRef<str>,
17559    {
17560        self._additional_params
17561            .insert(name.as_ref().to_string(), value.as_ref().to_string());
17562        self
17563    }
17564
17565    /// Identifies the authorization scope for the method you are building.
17566    ///
17567    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
17568    /// [`Scope::SettingBasic`].
17569    ///
17570    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
17571    /// tokens for more than one scope.
17572    ///
17573    /// Usually there is more than one suitable scope to authorize an operation, some of which may
17574    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
17575    /// sufficient, a read-write scope will do as well.
17576    pub fn add_scope<St>(mut self, scope: St) -> UserSettingFilterDeleteCall<'a, C>
17577    where
17578        St: AsRef<str>,
17579    {
17580        self._scopes.insert(String::from(scope.as_ref()));
17581        self
17582    }
17583    /// Identifies the authorization scope(s) for the method you are building.
17584    ///
17585    /// See [`Self::add_scope()`] for details.
17586    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingFilterDeleteCall<'a, C>
17587    where
17588        I: IntoIterator<Item = St>,
17589        St: AsRef<str>,
17590    {
17591        self._scopes
17592            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
17593        self
17594    }
17595
17596    /// Removes all scopes, and no default scope will be used either.
17597    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
17598    /// for details).
17599    pub fn clear_scopes(mut self) -> UserSettingFilterDeleteCall<'a, C> {
17600        self._scopes.clear();
17601        self
17602    }
17603}
17604
17605/// Gets a filter.
17606///
17607/// A builder for the *settings.filters.get* method supported by a *user* resource.
17608/// It is not used directly, but through a [`UserMethods`] instance.
17609///
17610/// # Example
17611///
17612/// Instantiate a resource method builder
17613///
17614/// ```test_harness,no_run
17615/// # extern crate hyper;
17616/// # extern crate hyper_rustls;
17617/// # extern crate google_gmail1 as gmail1;
17618/// # async fn dox() {
17619/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
17620///
17621/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
17622/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
17623/// #     secret,
17624/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
17625/// # ).build().await.unwrap();
17626///
17627/// # let client = hyper_util::client::legacy::Client::builder(
17628/// #     hyper_util::rt::TokioExecutor::new()
17629/// # )
17630/// # .build(
17631/// #     hyper_rustls::HttpsConnectorBuilder::new()
17632/// #         .with_native_roots()
17633/// #         .unwrap()
17634/// #         .https_or_http()
17635/// #         .enable_http1()
17636/// #         .build()
17637/// # );
17638/// # let mut hub = Gmail::new(client, auth);
17639/// // You can configure optional parameters by calling the respective setters at will, and
17640/// // execute the final call using `doit()`.
17641/// // Values shown here are possibly random and not representative !
17642/// let result = hub.users().settings_filters_get("userId", "id")
17643///              .doit().await;
17644/// # }
17645/// ```
17646pub struct UserSettingFilterGetCall<'a, C>
17647where
17648    C: 'a,
17649{
17650    hub: &'a Gmail<C>,
17651    _user_id: String,
17652    _id: String,
17653    _delegate: Option<&'a mut dyn common::Delegate>,
17654    _additional_params: HashMap<String, String>,
17655    _scopes: BTreeSet<String>,
17656}
17657
17658impl<'a, C> common::CallBuilder for UserSettingFilterGetCall<'a, C> {}
17659
17660impl<'a, C> UserSettingFilterGetCall<'a, C>
17661where
17662    C: common::Connector,
17663{
17664    /// Perform the operation you have build so far.
17665    pub async fn doit(mut self) -> common::Result<(common::Response, Filter)> {
17666        use std::borrow::Cow;
17667        use std::io::{Read, Seek};
17668
17669        use common::{url::Params, ToParts};
17670        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
17671
17672        let mut dd = common::DefaultDelegate;
17673        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
17674        dlg.begin(common::MethodInfo {
17675            id: "gmail.users.settings.filters.get",
17676            http_method: hyper::Method::GET,
17677        });
17678
17679        for &field in ["alt", "userId", "id"].iter() {
17680            if self._additional_params.contains_key(field) {
17681                dlg.finished(false);
17682                return Err(common::Error::FieldClash(field));
17683            }
17684        }
17685
17686        let mut params = Params::with_capacity(4 + self._additional_params.len());
17687        params.push("userId", self._user_id);
17688        params.push("id", self._id);
17689
17690        params.extend(self._additional_params.iter());
17691
17692        params.push("alt", "json");
17693        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/filters/{id}";
17694        if self._scopes.is_empty() {
17695            self._scopes.insert(Scope::Readonly.as_ref().to_string());
17696        }
17697
17698        #[allow(clippy::single_element_loop)]
17699        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
17700            url = params.uri_replacement(url, param_name, find_this, false);
17701        }
17702        {
17703            let to_remove = ["id", "userId"];
17704            params.remove_params(&to_remove);
17705        }
17706
17707        let url = params.parse_with_url(&url);
17708
17709        loop {
17710            let token = match self
17711                .hub
17712                .auth
17713                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
17714                .await
17715            {
17716                Ok(token) => token,
17717                Err(e) => match dlg.token(e) {
17718                    Ok(token) => token,
17719                    Err(e) => {
17720                        dlg.finished(false);
17721                        return Err(common::Error::MissingToken(e));
17722                    }
17723                },
17724            };
17725            let mut req_result = {
17726                let client = &self.hub.client;
17727                dlg.pre_request();
17728                let mut req_builder = hyper::Request::builder()
17729                    .method(hyper::Method::GET)
17730                    .uri(url.as_str())
17731                    .header(USER_AGENT, self.hub._user_agent.clone());
17732
17733                if let Some(token) = token.as_ref() {
17734                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
17735                }
17736
17737                let request = req_builder
17738                    .header(CONTENT_LENGTH, 0_u64)
17739                    .body(common::to_body::<String>(None));
17740
17741                client.request(request.unwrap()).await
17742            };
17743
17744            match req_result {
17745                Err(err) => {
17746                    if let common::Retry::After(d) = dlg.http_error(&err) {
17747                        sleep(d).await;
17748                        continue;
17749                    }
17750                    dlg.finished(false);
17751                    return Err(common::Error::HttpError(err));
17752                }
17753                Ok(res) => {
17754                    let (mut parts, body) = res.into_parts();
17755                    let mut body = common::Body::new(body);
17756                    if !parts.status.is_success() {
17757                        let bytes = common::to_bytes(body).await.unwrap_or_default();
17758                        let error = serde_json::from_str(&common::to_string(&bytes));
17759                        let response = common::to_response(parts, bytes.into());
17760
17761                        if let common::Retry::After(d) =
17762                            dlg.http_failure(&response, error.as_ref().ok())
17763                        {
17764                            sleep(d).await;
17765                            continue;
17766                        }
17767
17768                        dlg.finished(false);
17769
17770                        return Err(match error {
17771                            Ok(value) => common::Error::BadRequest(value),
17772                            _ => common::Error::Failure(response),
17773                        });
17774                    }
17775                    let response = {
17776                        let bytes = common::to_bytes(body).await.unwrap_or_default();
17777                        let encoded = common::to_string(&bytes);
17778                        match serde_json::from_str(&encoded) {
17779                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
17780                            Err(error) => {
17781                                dlg.response_json_decode_error(&encoded, &error);
17782                                return Err(common::Error::JsonDecodeError(
17783                                    encoded.to_string(),
17784                                    error,
17785                                ));
17786                            }
17787                        }
17788                    };
17789
17790                    dlg.finished(true);
17791                    return Ok(response);
17792                }
17793            }
17794        }
17795    }
17796
17797    /// User's email address. The special value "me" can be used to indicate the authenticated user.
17798    ///
17799    /// Sets the *user id* path property to the given value.
17800    ///
17801    /// Even though the property as already been set when instantiating this call,
17802    /// we provide this method for API completeness.
17803    pub fn user_id(mut self, new_value: &str) -> UserSettingFilterGetCall<'a, C> {
17804        self._user_id = new_value.to_string();
17805        self
17806    }
17807    /// The ID of the filter to be fetched.
17808    ///
17809    /// Sets the *id* path property to the given value.
17810    ///
17811    /// Even though the property as already been set when instantiating this call,
17812    /// we provide this method for API completeness.
17813    pub fn id(mut self, new_value: &str) -> UserSettingFilterGetCall<'a, C> {
17814        self._id = new_value.to_string();
17815        self
17816    }
17817    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
17818    /// while executing the actual API request.
17819    ///
17820    /// ````text
17821    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
17822    /// ````
17823    ///
17824    /// Sets the *delegate* property to the given value.
17825    pub fn delegate(
17826        mut self,
17827        new_value: &'a mut dyn common::Delegate,
17828    ) -> UserSettingFilterGetCall<'a, C> {
17829        self._delegate = Some(new_value);
17830        self
17831    }
17832
17833    /// Set any additional parameter of the query string used in the request.
17834    /// It should be used to set parameters which are not yet available through their own
17835    /// setters.
17836    ///
17837    /// Please note that this method must not be used to set any of the known parameters
17838    /// which have their own setter method. If done anyway, the request will fail.
17839    ///
17840    /// # Additional Parameters
17841    ///
17842    /// * *$.xgafv* (query-string) - V1 error format.
17843    /// * *access_token* (query-string) - OAuth access token.
17844    /// * *alt* (query-string) - Data format for response.
17845    /// * *callback* (query-string) - JSONP
17846    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
17847    /// * *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.
17848    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
17849    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
17850    /// * *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.
17851    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
17852    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
17853    pub fn param<T>(mut self, name: T, value: T) -> UserSettingFilterGetCall<'a, C>
17854    where
17855        T: AsRef<str>,
17856    {
17857        self._additional_params
17858            .insert(name.as_ref().to_string(), value.as_ref().to_string());
17859        self
17860    }
17861
17862    /// Identifies the authorization scope for the method you are building.
17863    ///
17864    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
17865    /// [`Scope::Readonly`].
17866    ///
17867    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
17868    /// tokens for more than one scope.
17869    ///
17870    /// Usually there is more than one suitable scope to authorize an operation, some of which may
17871    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
17872    /// sufficient, a read-write scope will do as well.
17873    pub fn add_scope<St>(mut self, scope: St) -> UserSettingFilterGetCall<'a, C>
17874    where
17875        St: AsRef<str>,
17876    {
17877        self._scopes.insert(String::from(scope.as_ref()));
17878        self
17879    }
17880    /// Identifies the authorization scope(s) for the method you are building.
17881    ///
17882    /// See [`Self::add_scope()`] for details.
17883    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingFilterGetCall<'a, C>
17884    where
17885        I: IntoIterator<Item = St>,
17886        St: AsRef<str>,
17887    {
17888        self._scopes
17889            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
17890        self
17891    }
17892
17893    /// Removes all scopes, and no default scope will be used either.
17894    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
17895    /// for details).
17896    pub fn clear_scopes(mut self) -> UserSettingFilterGetCall<'a, C> {
17897        self._scopes.clear();
17898        self
17899    }
17900}
17901
17902/// Lists the message filters of a Gmail user.
17903///
17904/// A builder for the *settings.filters.list* method supported by a *user* resource.
17905/// It is not used directly, but through a [`UserMethods`] instance.
17906///
17907/// # Example
17908///
17909/// Instantiate a resource method builder
17910///
17911/// ```test_harness,no_run
17912/// # extern crate hyper;
17913/// # extern crate hyper_rustls;
17914/// # extern crate google_gmail1 as gmail1;
17915/// # async fn dox() {
17916/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
17917///
17918/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
17919/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
17920/// #     secret,
17921/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
17922/// # ).build().await.unwrap();
17923///
17924/// # let client = hyper_util::client::legacy::Client::builder(
17925/// #     hyper_util::rt::TokioExecutor::new()
17926/// # )
17927/// # .build(
17928/// #     hyper_rustls::HttpsConnectorBuilder::new()
17929/// #         .with_native_roots()
17930/// #         .unwrap()
17931/// #         .https_or_http()
17932/// #         .enable_http1()
17933/// #         .build()
17934/// # );
17935/// # let mut hub = Gmail::new(client, auth);
17936/// // You can configure optional parameters by calling the respective setters at will, and
17937/// // execute the final call using `doit()`.
17938/// // Values shown here are possibly random and not representative !
17939/// let result = hub.users().settings_filters_list("userId")
17940///              .doit().await;
17941/// # }
17942/// ```
17943pub struct UserSettingFilterListCall<'a, C>
17944where
17945    C: 'a,
17946{
17947    hub: &'a Gmail<C>,
17948    _user_id: String,
17949    _delegate: Option<&'a mut dyn common::Delegate>,
17950    _additional_params: HashMap<String, String>,
17951    _scopes: BTreeSet<String>,
17952}
17953
17954impl<'a, C> common::CallBuilder for UserSettingFilterListCall<'a, C> {}
17955
17956impl<'a, C> UserSettingFilterListCall<'a, C>
17957where
17958    C: common::Connector,
17959{
17960    /// Perform the operation you have build so far.
17961    pub async fn doit(mut self) -> common::Result<(common::Response, ListFiltersResponse)> {
17962        use std::borrow::Cow;
17963        use std::io::{Read, Seek};
17964
17965        use common::{url::Params, ToParts};
17966        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
17967
17968        let mut dd = common::DefaultDelegate;
17969        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
17970        dlg.begin(common::MethodInfo {
17971            id: "gmail.users.settings.filters.list",
17972            http_method: hyper::Method::GET,
17973        });
17974
17975        for &field in ["alt", "userId"].iter() {
17976            if self._additional_params.contains_key(field) {
17977                dlg.finished(false);
17978                return Err(common::Error::FieldClash(field));
17979            }
17980        }
17981
17982        let mut params = Params::with_capacity(3 + self._additional_params.len());
17983        params.push("userId", self._user_id);
17984
17985        params.extend(self._additional_params.iter());
17986
17987        params.push("alt", "json");
17988        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/filters";
17989        if self._scopes.is_empty() {
17990            self._scopes.insert(Scope::Readonly.as_ref().to_string());
17991        }
17992
17993        #[allow(clippy::single_element_loop)]
17994        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
17995            url = params.uri_replacement(url, param_name, find_this, false);
17996        }
17997        {
17998            let to_remove = ["userId"];
17999            params.remove_params(&to_remove);
18000        }
18001
18002        let url = params.parse_with_url(&url);
18003
18004        loop {
18005            let token = match self
18006                .hub
18007                .auth
18008                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
18009                .await
18010            {
18011                Ok(token) => token,
18012                Err(e) => match dlg.token(e) {
18013                    Ok(token) => token,
18014                    Err(e) => {
18015                        dlg.finished(false);
18016                        return Err(common::Error::MissingToken(e));
18017                    }
18018                },
18019            };
18020            let mut req_result = {
18021                let client = &self.hub.client;
18022                dlg.pre_request();
18023                let mut req_builder = hyper::Request::builder()
18024                    .method(hyper::Method::GET)
18025                    .uri(url.as_str())
18026                    .header(USER_AGENT, self.hub._user_agent.clone());
18027
18028                if let Some(token) = token.as_ref() {
18029                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
18030                }
18031
18032                let request = req_builder
18033                    .header(CONTENT_LENGTH, 0_u64)
18034                    .body(common::to_body::<String>(None));
18035
18036                client.request(request.unwrap()).await
18037            };
18038
18039            match req_result {
18040                Err(err) => {
18041                    if let common::Retry::After(d) = dlg.http_error(&err) {
18042                        sleep(d).await;
18043                        continue;
18044                    }
18045                    dlg.finished(false);
18046                    return Err(common::Error::HttpError(err));
18047                }
18048                Ok(res) => {
18049                    let (mut parts, body) = res.into_parts();
18050                    let mut body = common::Body::new(body);
18051                    if !parts.status.is_success() {
18052                        let bytes = common::to_bytes(body).await.unwrap_or_default();
18053                        let error = serde_json::from_str(&common::to_string(&bytes));
18054                        let response = common::to_response(parts, bytes.into());
18055
18056                        if let common::Retry::After(d) =
18057                            dlg.http_failure(&response, error.as_ref().ok())
18058                        {
18059                            sleep(d).await;
18060                            continue;
18061                        }
18062
18063                        dlg.finished(false);
18064
18065                        return Err(match error {
18066                            Ok(value) => common::Error::BadRequest(value),
18067                            _ => common::Error::Failure(response),
18068                        });
18069                    }
18070                    let response = {
18071                        let bytes = common::to_bytes(body).await.unwrap_or_default();
18072                        let encoded = common::to_string(&bytes);
18073                        match serde_json::from_str(&encoded) {
18074                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
18075                            Err(error) => {
18076                                dlg.response_json_decode_error(&encoded, &error);
18077                                return Err(common::Error::JsonDecodeError(
18078                                    encoded.to_string(),
18079                                    error,
18080                                ));
18081                            }
18082                        }
18083                    };
18084
18085                    dlg.finished(true);
18086                    return Ok(response);
18087                }
18088            }
18089        }
18090    }
18091
18092    /// User's email address. The special value "me" can be used to indicate the authenticated user.
18093    ///
18094    /// Sets the *user id* path property to the given value.
18095    ///
18096    /// Even though the property as already been set when instantiating this call,
18097    /// we provide this method for API completeness.
18098    pub fn user_id(mut self, new_value: &str) -> UserSettingFilterListCall<'a, C> {
18099        self._user_id = new_value.to_string();
18100        self
18101    }
18102    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
18103    /// while executing the actual API request.
18104    ///
18105    /// ````text
18106    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
18107    /// ````
18108    ///
18109    /// Sets the *delegate* property to the given value.
18110    pub fn delegate(
18111        mut self,
18112        new_value: &'a mut dyn common::Delegate,
18113    ) -> UserSettingFilterListCall<'a, C> {
18114        self._delegate = Some(new_value);
18115        self
18116    }
18117
18118    /// Set any additional parameter of the query string used in the request.
18119    /// It should be used to set parameters which are not yet available through their own
18120    /// setters.
18121    ///
18122    /// Please note that this method must not be used to set any of the known parameters
18123    /// which have their own setter method. If done anyway, the request will fail.
18124    ///
18125    /// # Additional Parameters
18126    ///
18127    /// * *$.xgafv* (query-string) - V1 error format.
18128    /// * *access_token* (query-string) - OAuth access token.
18129    /// * *alt* (query-string) - Data format for response.
18130    /// * *callback* (query-string) - JSONP
18131    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
18132    /// * *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.
18133    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
18134    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
18135    /// * *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.
18136    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
18137    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
18138    pub fn param<T>(mut self, name: T, value: T) -> UserSettingFilterListCall<'a, C>
18139    where
18140        T: AsRef<str>,
18141    {
18142        self._additional_params
18143            .insert(name.as_ref().to_string(), value.as_ref().to_string());
18144        self
18145    }
18146
18147    /// Identifies the authorization scope for the method you are building.
18148    ///
18149    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
18150    /// [`Scope::Readonly`].
18151    ///
18152    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
18153    /// tokens for more than one scope.
18154    ///
18155    /// Usually there is more than one suitable scope to authorize an operation, some of which may
18156    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
18157    /// sufficient, a read-write scope will do as well.
18158    pub fn add_scope<St>(mut self, scope: St) -> UserSettingFilterListCall<'a, C>
18159    where
18160        St: AsRef<str>,
18161    {
18162        self._scopes.insert(String::from(scope.as_ref()));
18163        self
18164    }
18165    /// Identifies the authorization scope(s) for the method you are building.
18166    ///
18167    /// See [`Self::add_scope()`] for details.
18168    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingFilterListCall<'a, C>
18169    where
18170        I: IntoIterator<Item = St>,
18171        St: AsRef<str>,
18172    {
18173        self._scopes
18174            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
18175        self
18176    }
18177
18178    /// Removes all scopes, and no default scope will be used either.
18179    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
18180    /// for details).
18181    pub fn clear_scopes(mut self) -> UserSettingFilterListCall<'a, C> {
18182        self._scopes.clear();
18183        self
18184    }
18185}
18186
18187/// Creates a forwarding address. If ownership verification is required, a message will be sent to the recipient and the resource's verification status will be set to `pending`; otherwise, the resource will be created with verification status set to `accepted`. This method is only available to service account clients that have been delegated domain-wide authority.
18188///
18189/// A builder for the *settings.forwardingAddresses.create* method supported by a *user* resource.
18190/// It is not used directly, but through a [`UserMethods`] instance.
18191///
18192/// # Example
18193///
18194/// Instantiate a resource method builder
18195///
18196/// ```test_harness,no_run
18197/// # extern crate hyper;
18198/// # extern crate hyper_rustls;
18199/// # extern crate google_gmail1 as gmail1;
18200/// use gmail1::api::ForwardingAddress;
18201/// # async fn dox() {
18202/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
18203///
18204/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
18205/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
18206/// #     secret,
18207/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
18208/// # ).build().await.unwrap();
18209///
18210/// # let client = hyper_util::client::legacy::Client::builder(
18211/// #     hyper_util::rt::TokioExecutor::new()
18212/// # )
18213/// # .build(
18214/// #     hyper_rustls::HttpsConnectorBuilder::new()
18215/// #         .with_native_roots()
18216/// #         .unwrap()
18217/// #         .https_or_http()
18218/// #         .enable_http1()
18219/// #         .build()
18220/// # );
18221/// # let mut hub = Gmail::new(client, auth);
18222/// // As the method needs a request, you would usually fill it with the desired information
18223/// // into the respective structure. Some of the parts shown here might not be applicable !
18224/// // Values shown here are possibly random and not representative !
18225/// let mut req = ForwardingAddress::default();
18226///
18227/// // You can configure optional parameters by calling the respective setters at will, and
18228/// // execute the final call using `doit()`.
18229/// // Values shown here are possibly random and not representative !
18230/// let result = hub.users().settings_forwarding_addresses_create(req, "userId")
18231///              .doit().await;
18232/// # }
18233/// ```
18234pub struct UserSettingForwardingAddressCreateCall<'a, C>
18235where
18236    C: 'a,
18237{
18238    hub: &'a Gmail<C>,
18239    _request: ForwardingAddress,
18240    _user_id: String,
18241    _delegate: Option<&'a mut dyn common::Delegate>,
18242    _additional_params: HashMap<String, String>,
18243    _scopes: BTreeSet<String>,
18244}
18245
18246impl<'a, C> common::CallBuilder for UserSettingForwardingAddressCreateCall<'a, C> {}
18247
18248impl<'a, C> UserSettingForwardingAddressCreateCall<'a, C>
18249where
18250    C: common::Connector,
18251{
18252    /// Perform the operation you have build so far.
18253    pub async fn doit(mut self) -> common::Result<(common::Response, ForwardingAddress)> {
18254        use std::borrow::Cow;
18255        use std::io::{Read, Seek};
18256
18257        use common::{url::Params, ToParts};
18258        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
18259
18260        let mut dd = common::DefaultDelegate;
18261        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
18262        dlg.begin(common::MethodInfo {
18263            id: "gmail.users.settings.forwardingAddresses.create",
18264            http_method: hyper::Method::POST,
18265        });
18266
18267        for &field in ["alt", "userId"].iter() {
18268            if self._additional_params.contains_key(field) {
18269                dlg.finished(false);
18270                return Err(common::Error::FieldClash(field));
18271            }
18272        }
18273
18274        let mut params = Params::with_capacity(4 + self._additional_params.len());
18275        params.push("userId", self._user_id);
18276
18277        params.extend(self._additional_params.iter());
18278
18279        params.push("alt", "json");
18280        let mut url =
18281            self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/forwardingAddresses";
18282        if self._scopes.is_empty() {
18283            self._scopes
18284                .insert(Scope::SettingSharing.as_ref().to_string());
18285        }
18286
18287        #[allow(clippy::single_element_loop)]
18288        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
18289            url = params.uri_replacement(url, param_name, find_this, false);
18290        }
18291        {
18292            let to_remove = ["userId"];
18293            params.remove_params(&to_remove);
18294        }
18295
18296        let url = params.parse_with_url(&url);
18297
18298        let mut json_mime_type = mime::APPLICATION_JSON;
18299        let mut request_value_reader = {
18300            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
18301            common::remove_json_null_values(&mut value);
18302            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
18303            serde_json::to_writer(&mut dst, &value).unwrap();
18304            dst
18305        };
18306        let request_size = request_value_reader
18307            .seek(std::io::SeekFrom::End(0))
18308            .unwrap();
18309        request_value_reader
18310            .seek(std::io::SeekFrom::Start(0))
18311            .unwrap();
18312
18313        loop {
18314            let token = match self
18315                .hub
18316                .auth
18317                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
18318                .await
18319            {
18320                Ok(token) => token,
18321                Err(e) => match dlg.token(e) {
18322                    Ok(token) => token,
18323                    Err(e) => {
18324                        dlg.finished(false);
18325                        return Err(common::Error::MissingToken(e));
18326                    }
18327                },
18328            };
18329            request_value_reader
18330                .seek(std::io::SeekFrom::Start(0))
18331                .unwrap();
18332            let mut req_result = {
18333                let client = &self.hub.client;
18334                dlg.pre_request();
18335                let mut req_builder = hyper::Request::builder()
18336                    .method(hyper::Method::POST)
18337                    .uri(url.as_str())
18338                    .header(USER_AGENT, self.hub._user_agent.clone());
18339
18340                if let Some(token) = token.as_ref() {
18341                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
18342                }
18343
18344                let request = req_builder
18345                    .header(CONTENT_TYPE, json_mime_type.to_string())
18346                    .header(CONTENT_LENGTH, request_size as u64)
18347                    .body(common::to_body(
18348                        request_value_reader.get_ref().clone().into(),
18349                    ));
18350
18351                client.request(request.unwrap()).await
18352            };
18353
18354            match req_result {
18355                Err(err) => {
18356                    if let common::Retry::After(d) = dlg.http_error(&err) {
18357                        sleep(d).await;
18358                        continue;
18359                    }
18360                    dlg.finished(false);
18361                    return Err(common::Error::HttpError(err));
18362                }
18363                Ok(res) => {
18364                    let (mut parts, body) = res.into_parts();
18365                    let mut body = common::Body::new(body);
18366                    if !parts.status.is_success() {
18367                        let bytes = common::to_bytes(body).await.unwrap_or_default();
18368                        let error = serde_json::from_str(&common::to_string(&bytes));
18369                        let response = common::to_response(parts, bytes.into());
18370
18371                        if let common::Retry::After(d) =
18372                            dlg.http_failure(&response, error.as_ref().ok())
18373                        {
18374                            sleep(d).await;
18375                            continue;
18376                        }
18377
18378                        dlg.finished(false);
18379
18380                        return Err(match error {
18381                            Ok(value) => common::Error::BadRequest(value),
18382                            _ => common::Error::Failure(response),
18383                        });
18384                    }
18385                    let response = {
18386                        let bytes = common::to_bytes(body).await.unwrap_or_default();
18387                        let encoded = common::to_string(&bytes);
18388                        match serde_json::from_str(&encoded) {
18389                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
18390                            Err(error) => {
18391                                dlg.response_json_decode_error(&encoded, &error);
18392                                return Err(common::Error::JsonDecodeError(
18393                                    encoded.to_string(),
18394                                    error,
18395                                ));
18396                            }
18397                        }
18398                    };
18399
18400                    dlg.finished(true);
18401                    return Ok(response);
18402                }
18403            }
18404        }
18405    }
18406
18407    ///
18408    /// Sets the *request* property to the given value.
18409    ///
18410    /// Even though the property as already been set when instantiating this call,
18411    /// we provide this method for API completeness.
18412    pub fn request(
18413        mut self,
18414        new_value: ForwardingAddress,
18415    ) -> UserSettingForwardingAddressCreateCall<'a, C> {
18416        self._request = new_value;
18417        self
18418    }
18419    /// User's email address. The special value "me" can be used to indicate the authenticated user.
18420    ///
18421    /// Sets the *user id* path property to the given value.
18422    ///
18423    /// Even though the property as already been set when instantiating this call,
18424    /// we provide this method for API completeness.
18425    pub fn user_id(mut self, new_value: &str) -> UserSettingForwardingAddressCreateCall<'a, C> {
18426        self._user_id = new_value.to_string();
18427        self
18428    }
18429    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
18430    /// while executing the actual API request.
18431    ///
18432    /// ````text
18433    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
18434    /// ````
18435    ///
18436    /// Sets the *delegate* property to the given value.
18437    pub fn delegate(
18438        mut self,
18439        new_value: &'a mut dyn common::Delegate,
18440    ) -> UserSettingForwardingAddressCreateCall<'a, C> {
18441        self._delegate = Some(new_value);
18442        self
18443    }
18444
18445    /// Set any additional parameter of the query string used in the request.
18446    /// It should be used to set parameters which are not yet available through their own
18447    /// setters.
18448    ///
18449    /// Please note that this method must not be used to set any of the known parameters
18450    /// which have their own setter method. If done anyway, the request will fail.
18451    ///
18452    /// # Additional Parameters
18453    ///
18454    /// * *$.xgafv* (query-string) - V1 error format.
18455    /// * *access_token* (query-string) - OAuth access token.
18456    /// * *alt* (query-string) - Data format for response.
18457    /// * *callback* (query-string) - JSONP
18458    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
18459    /// * *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.
18460    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
18461    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
18462    /// * *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.
18463    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
18464    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
18465    pub fn param<T>(mut self, name: T, value: T) -> UserSettingForwardingAddressCreateCall<'a, C>
18466    where
18467        T: AsRef<str>,
18468    {
18469        self._additional_params
18470            .insert(name.as_ref().to_string(), value.as_ref().to_string());
18471        self
18472    }
18473
18474    /// Identifies the authorization scope for the method you are building.
18475    ///
18476    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
18477    /// [`Scope::SettingSharing`].
18478    ///
18479    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
18480    /// tokens for more than one scope.
18481    ///
18482    /// Usually there is more than one suitable scope to authorize an operation, some of which may
18483    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
18484    /// sufficient, a read-write scope will do as well.
18485    pub fn add_scope<St>(mut self, scope: St) -> UserSettingForwardingAddressCreateCall<'a, C>
18486    where
18487        St: AsRef<str>,
18488    {
18489        self._scopes.insert(String::from(scope.as_ref()));
18490        self
18491    }
18492    /// Identifies the authorization scope(s) for the method you are building.
18493    ///
18494    /// See [`Self::add_scope()`] for details.
18495    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingForwardingAddressCreateCall<'a, C>
18496    where
18497        I: IntoIterator<Item = St>,
18498        St: AsRef<str>,
18499    {
18500        self._scopes
18501            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
18502        self
18503    }
18504
18505    /// Removes all scopes, and no default scope will be used either.
18506    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
18507    /// for details).
18508    pub fn clear_scopes(mut self) -> UserSettingForwardingAddressCreateCall<'a, C> {
18509        self._scopes.clear();
18510        self
18511    }
18512}
18513
18514/// Deletes the specified forwarding address and revokes any verification that may have been required. This method is only available to service account clients that have been delegated domain-wide authority.
18515///
18516/// A builder for the *settings.forwardingAddresses.delete* method supported by a *user* resource.
18517/// It is not used directly, but through a [`UserMethods`] instance.
18518///
18519/// # Example
18520///
18521/// Instantiate a resource method builder
18522///
18523/// ```test_harness,no_run
18524/// # extern crate hyper;
18525/// # extern crate hyper_rustls;
18526/// # extern crate google_gmail1 as gmail1;
18527/// # async fn dox() {
18528/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
18529///
18530/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
18531/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
18532/// #     secret,
18533/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
18534/// # ).build().await.unwrap();
18535///
18536/// # let client = hyper_util::client::legacy::Client::builder(
18537/// #     hyper_util::rt::TokioExecutor::new()
18538/// # )
18539/// # .build(
18540/// #     hyper_rustls::HttpsConnectorBuilder::new()
18541/// #         .with_native_roots()
18542/// #         .unwrap()
18543/// #         .https_or_http()
18544/// #         .enable_http1()
18545/// #         .build()
18546/// # );
18547/// # let mut hub = Gmail::new(client, auth);
18548/// // You can configure optional parameters by calling the respective setters at will, and
18549/// // execute the final call using `doit()`.
18550/// // Values shown here are possibly random and not representative !
18551/// let result = hub.users().settings_forwarding_addresses_delete("userId", "forwardingEmail")
18552///              .doit().await;
18553/// # }
18554/// ```
18555pub struct UserSettingForwardingAddressDeleteCall<'a, C>
18556where
18557    C: 'a,
18558{
18559    hub: &'a Gmail<C>,
18560    _user_id: String,
18561    _forwarding_email: String,
18562    _delegate: Option<&'a mut dyn common::Delegate>,
18563    _additional_params: HashMap<String, String>,
18564    _scopes: BTreeSet<String>,
18565}
18566
18567impl<'a, C> common::CallBuilder for UserSettingForwardingAddressDeleteCall<'a, C> {}
18568
18569impl<'a, C> UserSettingForwardingAddressDeleteCall<'a, C>
18570where
18571    C: common::Connector,
18572{
18573    /// Perform the operation you have build so far.
18574    pub async fn doit(mut self) -> common::Result<common::Response> {
18575        use std::borrow::Cow;
18576        use std::io::{Read, Seek};
18577
18578        use common::{url::Params, ToParts};
18579        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
18580
18581        let mut dd = common::DefaultDelegate;
18582        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
18583        dlg.begin(common::MethodInfo {
18584            id: "gmail.users.settings.forwardingAddresses.delete",
18585            http_method: hyper::Method::DELETE,
18586        });
18587
18588        for &field in ["userId", "forwardingEmail"].iter() {
18589            if self._additional_params.contains_key(field) {
18590                dlg.finished(false);
18591                return Err(common::Error::FieldClash(field));
18592            }
18593        }
18594
18595        let mut params = Params::with_capacity(3 + self._additional_params.len());
18596        params.push("userId", self._user_id);
18597        params.push("forwardingEmail", self._forwarding_email);
18598
18599        params.extend(self._additional_params.iter());
18600
18601        let mut url = self.hub._base_url.clone()
18602            + "gmail/v1/users/{userId}/settings/forwardingAddresses/{forwardingEmail}";
18603        if self._scopes.is_empty() {
18604            self._scopes
18605                .insert(Scope::SettingSharing.as_ref().to_string());
18606        }
18607
18608        #[allow(clippy::single_element_loop)]
18609        for &(find_this, param_name) in [
18610            ("{userId}", "userId"),
18611            ("{forwardingEmail}", "forwardingEmail"),
18612        ]
18613        .iter()
18614        {
18615            url = params.uri_replacement(url, param_name, find_this, false);
18616        }
18617        {
18618            let to_remove = ["forwardingEmail", "userId"];
18619            params.remove_params(&to_remove);
18620        }
18621
18622        let url = params.parse_with_url(&url);
18623
18624        loop {
18625            let token = match self
18626                .hub
18627                .auth
18628                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
18629                .await
18630            {
18631                Ok(token) => token,
18632                Err(e) => match dlg.token(e) {
18633                    Ok(token) => token,
18634                    Err(e) => {
18635                        dlg.finished(false);
18636                        return Err(common::Error::MissingToken(e));
18637                    }
18638                },
18639            };
18640            let mut req_result = {
18641                let client = &self.hub.client;
18642                dlg.pre_request();
18643                let mut req_builder = hyper::Request::builder()
18644                    .method(hyper::Method::DELETE)
18645                    .uri(url.as_str())
18646                    .header(USER_AGENT, self.hub._user_agent.clone());
18647
18648                if let Some(token) = token.as_ref() {
18649                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
18650                }
18651
18652                let request = req_builder
18653                    .header(CONTENT_LENGTH, 0_u64)
18654                    .body(common::to_body::<String>(None));
18655
18656                client.request(request.unwrap()).await
18657            };
18658
18659            match req_result {
18660                Err(err) => {
18661                    if let common::Retry::After(d) = dlg.http_error(&err) {
18662                        sleep(d).await;
18663                        continue;
18664                    }
18665                    dlg.finished(false);
18666                    return Err(common::Error::HttpError(err));
18667                }
18668                Ok(res) => {
18669                    let (mut parts, body) = res.into_parts();
18670                    let mut body = common::Body::new(body);
18671                    if !parts.status.is_success() {
18672                        let bytes = common::to_bytes(body).await.unwrap_or_default();
18673                        let error = serde_json::from_str(&common::to_string(&bytes));
18674                        let response = common::to_response(parts, bytes.into());
18675
18676                        if let common::Retry::After(d) =
18677                            dlg.http_failure(&response, error.as_ref().ok())
18678                        {
18679                            sleep(d).await;
18680                            continue;
18681                        }
18682
18683                        dlg.finished(false);
18684
18685                        return Err(match error {
18686                            Ok(value) => common::Error::BadRequest(value),
18687                            _ => common::Error::Failure(response),
18688                        });
18689                    }
18690                    let response = common::Response::from_parts(parts, body);
18691
18692                    dlg.finished(true);
18693                    return Ok(response);
18694                }
18695            }
18696        }
18697    }
18698
18699    /// User's email address. The special value "me" can be used to indicate the authenticated user.
18700    ///
18701    /// Sets the *user id* path property to the given value.
18702    ///
18703    /// Even though the property as already been set when instantiating this call,
18704    /// we provide this method for API completeness.
18705    pub fn user_id(mut self, new_value: &str) -> UserSettingForwardingAddressDeleteCall<'a, C> {
18706        self._user_id = new_value.to_string();
18707        self
18708    }
18709    /// The forwarding address to be deleted.
18710    ///
18711    /// Sets the *forwarding email* path property to the given value.
18712    ///
18713    /// Even though the property as already been set when instantiating this call,
18714    /// we provide this method for API completeness.
18715    pub fn forwarding_email(
18716        mut self,
18717        new_value: &str,
18718    ) -> UserSettingForwardingAddressDeleteCall<'a, C> {
18719        self._forwarding_email = new_value.to_string();
18720        self
18721    }
18722    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
18723    /// while executing the actual API request.
18724    ///
18725    /// ````text
18726    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
18727    /// ````
18728    ///
18729    /// Sets the *delegate* property to the given value.
18730    pub fn delegate(
18731        mut self,
18732        new_value: &'a mut dyn common::Delegate,
18733    ) -> UserSettingForwardingAddressDeleteCall<'a, C> {
18734        self._delegate = Some(new_value);
18735        self
18736    }
18737
18738    /// Set any additional parameter of the query string used in the request.
18739    /// It should be used to set parameters which are not yet available through their own
18740    /// setters.
18741    ///
18742    /// Please note that this method must not be used to set any of the known parameters
18743    /// which have their own setter method. If done anyway, the request will fail.
18744    ///
18745    /// # Additional Parameters
18746    ///
18747    /// * *$.xgafv* (query-string) - V1 error format.
18748    /// * *access_token* (query-string) - OAuth access token.
18749    /// * *alt* (query-string) - Data format for response.
18750    /// * *callback* (query-string) - JSONP
18751    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
18752    /// * *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.
18753    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
18754    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
18755    /// * *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.
18756    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
18757    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
18758    pub fn param<T>(mut self, name: T, value: T) -> UserSettingForwardingAddressDeleteCall<'a, C>
18759    where
18760        T: AsRef<str>,
18761    {
18762        self._additional_params
18763            .insert(name.as_ref().to_string(), value.as_ref().to_string());
18764        self
18765    }
18766
18767    /// Identifies the authorization scope for the method you are building.
18768    ///
18769    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
18770    /// [`Scope::SettingSharing`].
18771    ///
18772    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
18773    /// tokens for more than one scope.
18774    ///
18775    /// Usually there is more than one suitable scope to authorize an operation, some of which may
18776    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
18777    /// sufficient, a read-write scope will do as well.
18778    pub fn add_scope<St>(mut self, scope: St) -> UserSettingForwardingAddressDeleteCall<'a, C>
18779    where
18780        St: AsRef<str>,
18781    {
18782        self._scopes.insert(String::from(scope.as_ref()));
18783        self
18784    }
18785    /// Identifies the authorization scope(s) for the method you are building.
18786    ///
18787    /// See [`Self::add_scope()`] for details.
18788    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingForwardingAddressDeleteCall<'a, C>
18789    where
18790        I: IntoIterator<Item = St>,
18791        St: AsRef<str>,
18792    {
18793        self._scopes
18794            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
18795        self
18796    }
18797
18798    /// Removes all scopes, and no default scope will be used either.
18799    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
18800    /// for details).
18801    pub fn clear_scopes(mut self) -> UserSettingForwardingAddressDeleteCall<'a, C> {
18802        self._scopes.clear();
18803        self
18804    }
18805}
18806
18807/// Gets the specified forwarding address.
18808///
18809/// A builder for the *settings.forwardingAddresses.get* method supported by a *user* resource.
18810/// It is not used directly, but through a [`UserMethods`] instance.
18811///
18812/// # Example
18813///
18814/// Instantiate a resource method builder
18815///
18816/// ```test_harness,no_run
18817/// # extern crate hyper;
18818/// # extern crate hyper_rustls;
18819/// # extern crate google_gmail1 as gmail1;
18820/// # async fn dox() {
18821/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
18822///
18823/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
18824/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
18825/// #     secret,
18826/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
18827/// # ).build().await.unwrap();
18828///
18829/// # let client = hyper_util::client::legacy::Client::builder(
18830/// #     hyper_util::rt::TokioExecutor::new()
18831/// # )
18832/// # .build(
18833/// #     hyper_rustls::HttpsConnectorBuilder::new()
18834/// #         .with_native_roots()
18835/// #         .unwrap()
18836/// #         .https_or_http()
18837/// #         .enable_http1()
18838/// #         .build()
18839/// # );
18840/// # let mut hub = Gmail::new(client, auth);
18841/// // You can configure optional parameters by calling the respective setters at will, and
18842/// // execute the final call using `doit()`.
18843/// // Values shown here are possibly random and not representative !
18844/// let result = hub.users().settings_forwarding_addresses_get("userId", "forwardingEmail")
18845///              .doit().await;
18846/// # }
18847/// ```
18848pub struct UserSettingForwardingAddressGetCall<'a, C>
18849where
18850    C: 'a,
18851{
18852    hub: &'a Gmail<C>,
18853    _user_id: String,
18854    _forwarding_email: String,
18855    _delegate: Option<&'a mut dyn common::Delegate>,
18856    _additional_params: HashMap<String, String>,
18857    _scopes: BTreeSet<String>,
18858}
18859
18860impl<'a, C> common::CallBuilder for UserSettingForwardingAddressGetCall<'a, C> {}
18861
18862impl<'a, C> UserSettingForwardingAddressGetCall<'a, C>
18863where
18864    C: common::Connector,
18865{
18866    /// Perform the operation you have build so far.
18867    pub async fn doit(mut self) -> common::Result<(common::Response, ForwardingAddress)> {
18868        use std::borrow::Cow;
18869        use std::io::{Read, Seek};
18870
18871        use common::{url::Params, ToParts};
18872        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
18873
18874        let mut dd = common::DefaultDelegate;
18875        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
18876        dlg.begin(common::MethodInfo {
18877            id: "gmail.users.settings.forwardingAddresses.get",
18878            http_method: hyper::Method::GET,
18879        });
18880
18881        for &field in ["alt", "userId", "forwardingEmail"].iter() {
18882            if self._additional_params.contains_key(field) {
18883                dlg.finished(false);
18884                return Err(common::Error::FieldClash(field));
18885            }
18886        }
18887
18888        let mut params = Params::with_capacity(4 + self._additional_params.len());
18889        params.push("userId", self._user_id);
18890        params.push("forwardingEmail", self._forwarding_email);
18891
18892        params.extend(self._additional_params.iter());
18893
18894        params.push("alt", "json");
18895        let mut url = self.hub._base_url.clone()
18896            + "gmail/v1/users/{userId}/settings/forwardingAddresses/{forwardingEmail}";
18897        if self._scopes.is_empty() {
18898            self._scopes.insert(Scope::Readonly.as_ref().to_string());
18899        }
18900
18901        #[allow(clippy::single_element_loop)]
18902        for &(find_this, param_name) in [
18903            ("{userId}", "userId"),
18904            ("{forwardingEmail}", "forwardingEmail"),
18905        ]
18906        .iter()
18907        {
18908            url = params.uri_replacement(url, param_name, find_this, false);
18909        }
18910        {
18911            let to_remove = ["forwardingEmail", "userId"];
18912            params.remove_params(&to_remove);
18913        }
18914
18915        let url = params.parse_with_url(&url);
18916
18917        loop {
18918            let token = match self
18919                .hub
18920                .auth
18921                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
18922                .await
18923            {
18924                Ok(token) => token,
18925                Err(e) => match dlg.token(e) {
18926                    Ok(token) => token,
18927                    Err(e) => {
18928                        dlg.finished(false);
18929                        return Err(common::Error::MissingToken(e));
18930                    }
18931                },
18932            };
18933            let mut req_result = {
18934                let client = &self.hub.client;
18935                dlg.pre_request();
18936                let mut req_builder = hyper::Request::builder()
18937                    .method(hyper::Method::GET)
18938                    .uri(url.as_str())
18939                    .header(USER_AGENT, self.hub._user_agent.clone());
18940
18941                if let Some(token) = token.as_ref() {
18942                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
18943                }
18944
18945                let request = req_builder
18946                    .header(CONTENT_LENGTH, 0_u64)
18947                    .body(common::to_body::<String>(None));
18948
18949                client.request(request.unwrap()).await
18950            };
18951
18952            match req_result {
18953                Err(err) => {
18954                    if let common::Retry::After(d) = dlg.http_error(&err) {
18955                        sleep(d).await;
18956                        continue;
18957                    }
18958                    dlg.finished(false);
18959                    return Err(common::Error::HttpError(err));
18960                }
18961                Ok(res) => {
18962                    let (mut parts, body) = res.into_parts();
18963                    let mut body = common::Body::new(body);
18964                    if !parts.status.is_success() {
18965                        let bytes = common::to_bytes(body).await.unwrap_or_default();
18966                        let error = serde_json::from_str(&common::to_string(&bytes));
18967                        let response = common::to_response(parts, bytes.into());
18968
18969                        if let common::Retry::After(d) =
18970                            dlg.http_failure(&response, error.as_ref().ok())
18971                        {
18972                            sleep(d).await;
18973                            continue;
18974                        }
18975
18976                        dlg.finished(false);
18977
18978                        return Err(match error {
18979                            Ok(value) => common::Error::BadRequest(value),
18980                            _ => common::Error::Failure(response),
18981                        });
18982                    }
18983                    let response = {
18984                        let bytes = common::to_bytes(body).await.unwrap_or_default();
18985                        let encoded = common::to_string(&bytes);
18986                        match serde_json::from_str(&encoded) {
18987                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
18988                            Err(error) => {
18989                                dlg.response_json_decode_error(&encoded, &error);
18990                                return Err(common::Error::JsonDecodeError(
18991                                    encoded.to_string(),
18992                                    error,
18993                                ));
18994                            }
18995                        }
18996                    };
18997
18998                    dlg.finished(true);
18999                    return Ok(response);
19000                }
19001            }
19002        }
19003    }
19004
19005    /// User's email address. The special value "me" can be used to indicate the authenticated user.
19006    ///
19007    /// Sets the *user id* path property to the given value.
19008    ///
19009    /// Even though the property as already been set when instantiating this call,
19010    /// we provide this method for API completeness.
19011    pub fn user_id(mut self, new_value: &str) -> UserSettingForwardingAddressGetCall<'a, C> {
19012        self._user_id = new_value.to_string();
19013        self
19014    }
19015    /// The forwarding address to be retrieved.
19016    ///
19017    /// Sets the *forwarding email* path property to the given value.
19018    ///
19019    /// Even though the property as already been set when instantiating this call,
19020    /// we provide this method for API completeness.
19021    pub fn forwarding_email(
19022        mut self,
19023        new_value: &str,
19024    ) -> UserSettingForwardingAddressGetCall<'a, C> {
19025        self._forwarding_email = new_value.to_string();
19026        self
19027    }
19028    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
19029    /// while executing the actual API request.
19030    ///
19031    /// ````text
19032    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
19033    /// ````
19034    ///
19035    /// Sets the *delegate* property to the given value.
19036    pub fn delegate(
19037        mut self,
19038        new_value: &'a mut dyn common::Delegate,
19039    ) -> UserSettingForwardingAddressGetCall<'a, C> {
19040        self._delegate = Some(new_value);
19041        self
19042    }
19043
19044    /// Set any additional parameter of the query string used in the request.
19045    /// It should be used to set parameters which are not yet available through their own
19046    /// setters.
19047    ///
19048    /// Please note that this method must not be used to set any of the known parameters
19049    /// which have their own setter method. If done anyway, the request will fail.
19050    ///
19051    /// # Additional Parameters
19052    ///
19053    /// * *$.xgafv* (query-string) - V1 error format.
19054    /// * *access_token* (query-string) - OAuth access token.
19055    /// * *alt* (query-string) - Data format for response.
19056    /// * *callback* (query-string) - JSONP
19057    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
19058    /// * *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.
19059    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
19060    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
19061    /// * *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.
19062    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
19063    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
19064    pub fn param<T>(mut self, name: T, value: T) -> UserSettingForwardingAddressGetCall<'a, C>
19065    where
19066        T: AsRef<str>,
19067    {
19068        self._additional_params
19069            .insert(name.as_ref().to_string(), value.as_ref().to_string());
19070        self
19071    }
19072
19073    /// Identifies the authorization scope for the method you are building.
19074    ///
19075    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
19076    /// [`Scope::Readonly`].
19077    ///
19078    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
19079    /// tokens for more than one scope.
19080    ///
19081    /// Usually there is more than one suitable scope to authorize an operation, some of which may
19082    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
19083    /// sufficient, a read-write scope will do as well.
19084    pub fn add_scope<St>(mut self, scope: St) -> UserSettingForwardingAddressGetCall<'a, C>
19085    where
19086        St: AsRef<str>,
19087    {
19088        self._scopes.insert(String::from(scope.as_ref()));
19089        self
19090    }
19091    /// Identifies the authorization scope(s) for the method you are building.
19092    ///
19093    /// See [`Self::add_scope()`] for details.
19094    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingForwardingAddressGetCall<'a, C>
19095    where
19096        I: IntoIterator<Item = St>,
19097        St: AsRef<str>,
19098    {
19099        self._scopes
19100            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
19101        self
19102    }
19103
19104    /// Removes all scopes, and no default scope will be used either.
19105    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
19106    /// for details).
19107    pub fn clear_scopes(mut self) -> UserSettingForwardingAddressGetCall<'a, C> {
19108        self._scopes.clear();
19109        self
19110    }
19111}
19112
19113/// Lists the forwarding addresses for the specified account.
19114///
19115/// A builder for the *settings.forwardingAddresses.list* method supported by a *user* resource.
19116/// It is not used directly, but through a [`UserMethods`] instance.
19117///
19118/// # Example
19119///
19120/// Instantiate a resource method builder
19121///
19122/// ```test_harness,no_run
19123/// # extern crate hyper;
19124/// # extern crate hyper_rustls;
19125/// # extern crate google_gmail1 as gmail1;
19126/// # async fn dox() {
19127/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
19128///
19129/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
19130/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
19131/// #     secret,
19132/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
19133/// # ).build().await.unwrap();
19134///
19135/// # let client = hyper_util::client::legacy::Client::builder(
19136/// #     hyper_util::rt::TokioExecutor::new()
19137/// # )
19138/// # .build(
19139/// #     hyper_rustls::HttpsConnectorBuilder::new()
19140/// #         .with_native_roots()
19141/// #         .unwrap()
19142/// #         .https_or_http()
19143/// #         .enable_http1()
19144/// #         .build()
19145/// # );
19146/// # let mut hub = Gmail::new(client, auth);
19147/// // You can configure optional parameters by calling the respective setters at will, and
19148/// // execute the final call using `doit()`.
19149/// // Values shown here are possibly random and not representative !
19150/// let result = hub.users().settings_forwarding_addresses_list("userId")
19151///              .doit().await;
19152/// # }
19153/// ```
19154pub struct UserSettingForwardingAddressListCall<'a, C>
19155where
19156    C: 'a,
19157{
19158    hub: &'a Gmail<C>,
19159    _user_id: String,
19160    _delegate: Option<&'a mut dyn common::Delegate>,
19161    _additional_params: HashMap<String, String>,
19162    _scopes: BTreeSet<String>,
19163}
19164
19165impl<'a, C> common::CallBuilder for UserSettingForwardingAddressListCall<'a, C> {}
19166
19167impl<'a, C> UserSettingForwardingAddressListCall<'a, C>
19168where
19169    C: common::Connector,
19170{
19171    /// Perform the operation you have build so far.
19172    pub async fn doit(
19173        mut self,
19174    ) -> common::Result<(common::Response, ListForwardingAddressesResponse)> {
19175        use std::borrow::Cow;
19176        use std::io::{Read, Seek};
19177
19178        use common::{url::Params, ToParts};
19179        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
19180
19181        let mut dd = common::DefaultDelegate;
19182        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
19183        dlg.begin(common::MethodInfo {
19184            id: "gmail.users.settings.forwardingAddresses.list",
19185            http_method: hyper::Method::GET,
19186        });
19187
19188        for &field in ["alt", "userId"].iter() {
19189            if self._additional_params.contains_key(field) {
19190                dlg.finished(false);
19191                return Err(common::Error::FieldClash(field));
19192            }
19193        }
19194
19195        let mut params = Params::with_capacity(3 + self._additional_params.len());
19196        params.push("userId", self._user_id);
19197
19198        params.extend(self._additional_params.iter());
19199
19200        params.push("alt", "json");
19201        let mut url =
19202            self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/forwardingAddresses";
19203        if self._scopes.is_empty() {
19204            self._scopes.insert(Scope::Readonly.as_ref().to_string());
19205        }
19206
19207        #[allow(clippy::single_element_loop)]
19208        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
19209            url = params.uri_replacement(url, param_name, find_this, false);
19210        }
19211        {
19212            let to_remove = ["userId"];
19213            params.remove_params(&to_remove);
19214        }
19215
19216        let url = params.parse_with_url(&url);
19217
19218        loop {
19219            let token = match self
19220                .hub
19221                .auth
19222                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
19223                .await
19224            {
19225                Ok(token) => token,
19226                Err(e) => match dlg.token(e) {
19227                    Ok(token) => token,
19228                    Err(e) => {
19229                        dlg.finished(false);
19230                        return Err(common::Error::MissingToken(e));
19231                    }
19232                },
19233            };
19234            let mut req_result = {
19235                let client = &self.hub.client;
19236                dlg.pre_request();
19237                let mut req_builder = hyper::Request::builder()
19238                    .method(hyper::Method::GET)
19239                    .uri(url.as_str())
19240                    .header(USER_AGENT, self.hub._user_agent.clone());
19241
19242                if let Some(token) = token.as_ref() {
19243                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
19244                }
19245
19246                let request = req_builder
19247                    .header(CONTENT_LENGTH, 0_u64)
19248                    .body(common::to_body::<String>(None));
19249
19250                client.request(request.unwrap()).await
19251            };
19252
19253            match req_result {
19254                Err(err) => {
19255                    if let common::Retry::After(d) = dlg.http_error(&err) {
19256                        sleep(d).await;
19257                        continue;
19258                    }
19259                    dlg.finished(false);
19260                    return Err(common::Error::HttpError(err));
19261                }
19262                Ok(res) => {
19263                    let (mut parts, body) = res.into_parts();
19264                    let mut body = common::Body::new(body);
19265                    if !parts.status.is_success() {
19266                        let bytes = common::to_bytes(body).await.unwrap_or_default();
19267                        let error = serde_json::from_str(&common::to_string(&bytes));
19268                        let response = common::to_response(parts, bytes.into());
19269
19270                        if let common::Retry::After(d) =
19271                            dlg.http_failure(&response, error.as_ref().ok())
19272                        {
19273                            sleep(d).await;
19274                            continue;
19275                        }
19276
19277                        dlg.finished(false);
19278
19279                        return Err(match error {
19280                            Ok(value) => common::Error::BadRequest(value),
19281                            _ => common::Error::Failure(response),
19282                        });
19283                    }
19284                    let response = {
19285                        let bytes = common::to_bytes(body).await.unwrap_or_default();
19286                        let encoded = common::to_string(&bytes);
19287                        match serde_json::from_str(&encoded) {
19288                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
19289                            Err(error) => {
19290                                dlg.response_json_decode_error(&encoded, &error);
19291                                return Err(common::Error::JsonDecodeError(
19292                                    encoded.to_string(),
19293                                    error,
19294                                ));
19295                            }
19296                        }
19297                    };
19298
19299                    dlg.finished(true);
19300                    return Ok(response);
19301                }
19302            }
19303        }
19304    }
19305
19306    /// User's email address. The special value "me" can be used to indicate the authenticated user.
19307    ///
19308    /// Sets the *user id* path property to the given value.
19309    ///
19310    /// Even though the property as already been set when instantiating this call,
19311    /// we provide this method for API completeness.
19312    pub fn user_id(mut self, new_value: &str) -> UserSettingForwardingAddressListCall<'a, C> {
19313        self._user_id = new_value.to_string();
19314        self
19315    }
19316    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
19317    /// while executing the actual API request.
19318    ///
19319    /// ````text
19320    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
19321    /// ````
19322    ///
19323    /// Sets the *delegate* property to the given value.
19324    pub fn delegate(
19325        mut self,
19326        new_value: &'a mut dyn common::Delegate,
19327    ) -> UserSettingForwardingAddressListCall<'a, C> {
19328        self._delegate = Some(new_value);
19329        self
19330    }
19331
19332    /// Set any additional parameter of the query string used in the request.
19333    /// It should be used to set parameters which are not yet available through their own
19334    /// setters.
19335    ///
19336    /// Please note that this method must not be used to set any of the known parameters
19337    /// which have their own setter method. If done anyway, the request will fail.
19338    ///
19339    /// # Additional Parameters
19340    ///
19341    /// * *$.xgafv* (query-string) - V1 error format.
19342    /// * *access_token* (query-string) - OAuth access token.
19343    /// * *alt* (query-string) - Data format for response.
19344    /// * *callback* (query-string) - JSONP
19345    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
19346    /// * *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.
19347    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
19348    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
19349    /// * *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.
19350    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
19351    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
19352    pub fn param<T>(mut self, name: T, value: T) -> UserSettingForwardingAddressListCall<'a, C>
19353    where
19354        T: AsRef<str>,
19355    {
19356        self._additional_params
19357            .insert(name.as_ref().to_string(), value.as_ref().to_string());
19358        self
19359    }
19360
19361    /// Identifies the authorization scope for the method you are building.
19362    ///
19363    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
19364    /// [`Scope::Readonly`].
19365    ///
19366    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
19367    /// tokens for more than one scope.
19368    ///
19369    /// Usually there is more than one suitable scope to authorize an operation, some of which may
19370    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
19371    /// sufficient, a read-write scope will do as well.
19372    pub fn add_scope<St>(mut self, scope: St) -> UserSettingForwardingAddressListCall<'a, C>
19373    where
19374        St: AsRef<str>,
19375    {
19376        self._scopes.insert(String::from(scope.as_ref()));
19377        self
19378    }
19379    /// Identifies the authorization scope(s) for the method you are building.
19380    ///
19381    /// See [`Self::add_scope()`] for details.
19382    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingForwardingAddressListCall<'a, C>
19383    where
19384        I: IntoIterator<Item = St>,
19385        St: AsRef<str>,
19386    {
19387        self._scopes
19388            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
19389        self
19390    }
19391
19392    /// Removes all scopes, and no default scope will be used either.
19393    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
19394    /// for details).
19395    pub fn clear_scopes(mut self) -> UserSettingForwardingAddressListCall<'a, C> {
19396        self._scopes.clear();
19397        self
19398    }
19399}
19400
19401/// Deletes the specified S/MIME config for the specified send-as alias.
19402///
19403/// A builder for the *settings.sendAs.smimeInfo.delete* method supported by a *user* resource.
19404/// It is not used directly, but through a [`UserMethods`] instance.
19405///
19406/// # Example
19407///
19408/// Instantiate a resource method builder
19409///
19410/// ```test_harness,no_run
19411/// # extern crate hyper;
19412/// # extern crate hyper_rustls;
19413/// # extern crate google_gmail1 as gmail1;
19414/// # async fn dox() {
19415/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
19416///
19417/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
19418/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
19419/// #     secret,
19420/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
19421/// # ).build().await.unwrap();
19422///
19423/// # let client = hyper_util::client::legacy::Client::builder(
19424/// #     hyper_util::rt::TokioExecutor::new()
19425/// # )
19426/// # .build(
19427/// #     hyper_rustls::HttpsConnectorBuilder::new()
19428/// #         .with_native_roots()
19429/// #         .unwrap()
19430/// #         .https_or_http()
19431/// #         .enable_http1()
19432/// #         .build()
19433/// # );
19434/// # let mut hub = Gmail::new(client, auth);
19435/// // You can configure optional parameters by calling the respective setters at will, and
19436/// // execute the final call using `doit()`.
19437/// // Values shown here are possibly random and not representative !
19438/// let result = hub.users().settings_send_as_smime_info_delete("userId", "sendAsEmail", "id")
19439///              .doit().await;
19440/// # }
19441/// ```
19442pub struct UserSettingSendASmimeInfoDeleteCall<'a, C>
19443where
19444    C: 'a,
19445{
19446    hub: &'a Gmail<C>,
19447    _user_id: String,
19448    _send_as_email: String,
19449    _id: String,
19450    _delegate: Option<&'a mut dyn common::Delegate>,
19451    _additional_params: HashMap<String, String>,
19452    _scopes: BTreeSet<String>,
19453}
19454
19455impl<'a, C> common::CallBuilder for UserSettingSendASmimeInfoDeleteCall<'a, C> {}
19456
19457impl<'a, C> UserSettingSendASmimeInfoDeleteCall<'a, C>
19458where
19459    C: common::Connector,
19460{
19461    /// Perform the operation you have build so far.
19462    pub async fn doit(mut self) -> common::Result<common::Response> {
19463        use std::borrow::Cow;
19464        use std::io::{Read, Seek};
19465
19466        use common::{url::Params, ToParts};
19467        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
19468
19469        let mut dd = common::DefaultDelegate;
19470        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
19471        dlg.begin(common::MethodInfo {
19472            id: "gmail.users.settings.sendAs.smimeInfo.delete",
19473            http_method: hyper::Method::DELETE,
19474        });
19475
19476        for &field in ["userId", "sendAsEmail", "id"].iter() {
19477            if self._additional_params.contains_key(field) {
19478                dlg.finished(false);
19479                return Err(common::Error::FieldClash(field));
19480            }
19481        }
19482
19483        let mut params = Params::with_capacity(4 + self._additional_params.len());
19484        params.push("userId", self._user_id);
19485        params.push("sendAsEmail", self._send_as_email);
19486        params.push("id", self._id);
19487
19488        params.extend(self._additional_params.iter());
19489
19490        let mut url = self.hub._base_url.clone()
19491            + "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo/{id}";
19492        if self._scopes.is_empty() {
19493            self._scopes
19494                .insert(Scope::SettingBasic.as_ref().to_string());
19495        }
19496
19497        #[allow(clippy::single_element_loop)]
19498        for &(find_this, param_name) in [
19499            ("{userId}", "userId"),
19500            ("{sendAsEmail}", "sendAsEmail"),
19501            ("{id}", "id"),
19502        ]
19503        .iter()
19504        {
19505            url = params.uri_replacement(url, param_name, find_this, false);
19506        }
19507        {
19508            let to_remove = ["id", "sendAsEmail", "userId"];
19509            params.remove_params(&to_remove);
19510        }
19511
19512        let url = params.parse_with_url(&url);
19513
19514        loop {
19515            let token = match self
19516                .hub
19517                .auth
19518                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
19519                .await
19520            {
19521                Ok(token) => token,
19522                Err(e) => match dlg.token(e) {
19523                    Ok(token) => token,
19524                    Err(e) => {
19525                        dlg.finished(false);
19526                        return Err(common::Error::MissingToken(e));
19527                    }
19528                },
19529            };
19530            let mut req_result = {
19531                let client = &self.hub.client;
19532                dlg.pre_request();
19533                let mut req_builder = hyper::Request::builder()
19534                    .method(hyper::Method::DELETE)
19535                    .uri(url.as_str())
19536                    .header(USER_AGENT, self.hub._user_agent.clone());
19537
19538                if let Some(token) = token.as_ref() {
19539                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
19540                }
19541
19542                let request = req_builder
19543                    .header(CONTENT_LENGTH, 0_u64)
19544                    .body(common::to_body::<String>(None));
19545
19546                client.request(request.unwrap()).await
19547            };
19548
19549            match req_result {
19550                Err(err) => {
19551                    if let common::Retry::After(d) = dlg.http_error(&err) {
19552                        sleep(d).await;
19553                        continue;
19554                    }
19555                    dlg.finished(false);
19556                    return Err(common::Error::HttpError(err));
19557                }
19558                Ok(res) => {
19559                    let (mut parts, body) = res.into_parts();
19560                    let mut body = common::Body::new(body);
19561                    if !parts.status.is_success() {
19562                        let bytes = common::to_bytes(body).await.unwrap_or_default();
19563                        let error = serde_json::from_str(&common::to_string(&bytes));
19564                        let response = common::to_response(parts, bytes.into());
19565
19566                        if let common::Retry::After(d) =
19567                            dlg.http_failure(&response, error.as_ref().ok())
19568                        {
19569                            sleep(d).await;
19570                            continue;
19571                        }
19572
19573                        dlg.finished(false);
19574
19575                        return Err(match error {
19576                            Ok(value) => common::Error::BadRequest(value),
19577                            _ => common::Error::Failure(response),
19578                        });
19579                    }
19580                    let response = common::Response::from_parts(parts, body);
19581
19582                    dlg.finished(true);
19583                    return Ok(response);
19584                }
19585            }
19586        }
19587    }
19588
19589    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
19590    ///
19591    /// Sets the *user id* path property to the given value.
19592    ///
19593    /// Even though the property as already been set when instantiating this call,
19594    /// we provide this method for API completeness.
19595    pub fn user_id(mut self, new_value: &str) -> UserSettingSendASmimeInfoDeleteCall<'a, C> {
19596        self._user_id = new_value.to_string();
19597        self
19598    }
19599    /// The email address that appears in the "From:" header for mail sent using this alias.
19600    ///
19601    /// Sets the *send as email* path property to the given value.
19602    ///
19603    /// Even though the property as already been set when instantiating this call,
19604    /// we provide this method for API completeness.
19605    pub fn send_as_email(mut self, new_value: &str) -> UserSettingSendASmimeInfoDeleteCall<'a, C> {
19606        self._send_as_email = new_value.to_string();
19607        self
19608    }
19609    /// The immutable ID for the SmimeInfo.
19610    ///
19611    /// Sets the *id* path property to the given value.
19612    ///
19613    /// Even though the property as already been set when instantiating this call,
19614    /// we provide this method for API completeness.
19615    pub fn id(mut self, new_value: &str) -> UserSettingSendASmimeInfoDeleteCall<'a, C> {
19616        self._id = new_value.to_string();
19617        self
19618    }
19619    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
19620    /// while executing the actual API request.
19621    ///
19622    /// ````text
19623    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
19624    /// ````
19625    ///
19626    /// Sets the *delegate* property to the given value.
19627    pub fn delegate(
19628        mut self,
19629        new_value: &'a mut dyn common::Delegate,
19630    ) -> UserSettingSendASmimeInfoDeleteCall<'a, C> {
19631        self._delegate = Some(new_value);
19632        self
19633    }
19634
19635    /// Set any additional parameter of the query string used in the request.
19636    /// It should be used to set parameters which are not yet available through their own
19637    /// setters.
19638    ///
19639    /// Please note that this method must not be used to set any of the known parameters
19640    /// which have their own setter method. If done anyway, the request will fail.
19641    ///
19642    /// # Additional Parameters
19643    ///
19644    /// * *$.xgafv* (query-string) - V1 error format.
19645    /// * *access_token* (query-string) - OAuth access token.
19646    /// * *alt* (query-string) - Data format for response.
19647    /// * *callback* (query-string) - JSONP
19648    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
19649    /// * *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.
19650    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
19651    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
19652    /// * *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.
19653    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
19654    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
19655    pub fn param<T>(mut self, name: T, value: T) -> UserSettingSendASmimeInfoDeleteCall<'a, C>
19656    where
19657        T: AsRef<str>,
19658    {
19659        self._additional_params
19660            .insert(name.as_ref().to_string(), value.as_ref().to_string());
19661        self
19662    }
19663
19664    /// Identifies the authorization scope for the method you are building.
19665    ///
19666    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
19667    /// [`Scope::SettingBasic`].
19668    ///
19669    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
19670    /// tokens for more than one scope.
19671    ///
19672    /// Usually there is more than one suitable scope to authorize an operation, some of which may
19673    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
19674    /// sufficient, a read-write scope will do as well.
19675    pub fn add_scope<St>(mut self, scope: St) -> UserSettingSendASmimeInfoDeleteCall<'a, C>
19676    where
19677        St: AsRef<str>,
19678    {
19679        self._scopes.insert(String::from(scope.as_ref()));
19680        self
19681    }
19682    /// Identifies the authorization scope(s) for the method you are building.
19683    ///
19684    /// See [`Self::add_scope()`] for details.
19685    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingSendASmimeInfoDeleteCall<'a, C>
19686    where
19687        I: IntoIterator<Item = St>,
19688        St: AsRef<str>,
19689    {
19690        self._scopes
19691            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
19692        self
19693    }
19694
19695    /// Removes all scopes, and no default scope will be used either.
19696    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
19697    /// for details).
19698    pub fn clear_scopes(mut self) -> UserSettingSendASmimeInfoDeleteCall<'a, C> {
19699        self._scopes.clear();
19700        self
19701    }
19702}
19703
19704/// Gets the specified S/MIME config for the specified send-as alias.
19705///
19706/// A builder for the *settings.sendAs.smimeInfo.get* method supported by a *user* resource.
19707/// It is not used directly, but through a [`UserMethods`] instance.
19708///
19709/// # Example
19710///
19711/// Instantiate a resource method builder
19712///
19713/// ```test_harness,no_run
19714/// # extern crate hyper;
19715/// # extern crate hyper_rustls;
19716/// # extern crate google_gmail1 as gmail1;
19717/// # async fn dox() {
19718/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
19719///
19720/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
19721/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
19722/// #     secret,
19723/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
19724/// # ).build().await.unwrap();
19725///
19726/// # let client = hyper_util::client::legacy::Client::builder(
19727/// #     hyper_util::rt::TokioExecutor::new()
19728/// # )
19729/// # .build(
19730/// #     hyper_rustls::HttpsConnectorBuilder::new()
19731/// #         .with_native_roots()
19732/// #         .unwrap()
19733/// #         .https_or_http()
19734/// #         .enable_http1()
19735/// #         .build()
19736/// # );
19737/// # let mut hub = Gmail::new(client, auth);
19738/// // You can configure optional parameters by calling the respective setters at will, and
19739/// // execute the final call using `doit()`.
19740/// // Values shown here are possibly random and not representative !
19741/// let result = hub.users().settings_send_as_smime_info_get("userId", "sendAsEmail", "id")
19742///              .doit().await;
19743/// # }
19744/// ```
19745pub struct UserSettingSendASmimeInfoGetCall<'a, C>
19746where
19747    C: 'a,
19748{
19749    hub: &'a Gmail<C>,
19750    _user_id: String,
19751    _send_as_email: String,
19752    _id: String,
19753    _delegate: Option<&'a mut dyn common::Delegate>,
19754    _additional_params: HashMap<String, String>,
19755    _scopes: BTreeSet<String>,
19756}
19757
19758impl<'a, C> common::CallBuilder for UserSettingSendASmimeInfoGetCall<'a, C> {}
19759
19760impl<'a, C> UserSettingSendASmimeInfoGetCall<'a, C>
19761where
19762    C: common::Connector,
19763{
19764    /// Perform the operation you have build so far.
19765    pub async fn doit(mut self) -> common::Result<(common::Response, SmimeInfo)> {
19766        use std::borrow::Cow;
19767        use std::io::{Read, Seek};
19768
19769        use common::{url::Params, ToParts};
19770        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
19771
19772        let mut dd = common::DefaultDelegate;
19773        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
19774        dlg.begin(common::MethodInfo {
19775            id: "gmail.users.settings.sendAs.smimeInfo.get",
19776            http_method: hyper::Method::GET,
19777        });
19778
19779        for &field in ["alt", "userId", "sendAsEmail", "id"].iter() {
19780            if self._additional_params.contains_key(field) {
19781                dlg.finished(false);
19782                return Err(common::Error::FieldClash(field));
19783            }
19784        }
19785
19786        let mut params = Params::with_capacity(5 + self._additional_params.len());
19787        params.push("userId", self._user_id);
19788        params.push("sendAsEmail", self._send_as_email);
19789        params.push("id", self._id);
19790
19791        params.extend(self._additional_params.iter());
19792
19793        params.push("alt", "json");
19794        let mut url = self.hub._base_url.clone()
19795            + "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo/{id}";
19796        if self._scopes.is_empty() {
19797            self._scopes.insert(Scope::Readonly.as_ref().to_string());
19798        }
19799
19800        #[allow(clippy::single_element_loop)]
19801        for &(find_this, param_name) in [
19802            ("{userId}", "userId"),
19803            ("{sendAsEmail}", "sendAsEmail"),
19804            ("{id}", "id"),
19805        ]
19806        .iter()
19807        {
19808            url = params.uri_replacement(url, param_name, find_this, false);
19809        }
19810        {
19811            let to_remove = ["id", "sendAsEmail", "userId"];
19812            params.remove_params(&to_remove);
19813        }
19814
19815        let url = params.parse_with_url(&url);
19816
19817        loop {
19818            let token = match self
19819                .hub
19820                .auth
19821                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
19822                .await
19823            {
19824                Ok(token) => token,
19825                Err(e) => match dlg.token(e) {
19826                    Ok(token) => token,
19827                    Err(e) => {
19828                        dlg.finished(false);
19829                        return Err(common::Error::MissingToken(e));
19830                    }
19831                },
19832            };
19833            let mut req_result = {
19834                let client = &self.hub.client;
19835                dlg.pre_request();
19836                let mut req_builder = hyper::Request::builder()
19837                    .method(hyper::Method::GET)
19838                    .uri(url.as_str())
19839                    .header(USER_AGENT, self.hub._user_agent.clone());
19840
19841                if let Some(token) = token.as_ref() {
19842                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
19843                }
19844
19845                let request = req_builder
19846                    .header(CONTENT_LENGTH, 0_u64)
19847                    .body(common::to_body::<String>(None));
19848
19849                client.request(request.unwrap()).await
19850            };
19851
19852            match req_result {
19853                Err(err) => {
19854                    if let common::Retry::After(d) = dlg.http_error(&err) {
19855                        sleep(d).await;
19856                        continue;
19857                    }
19858                    dlg.finished(false);
19859                    return Err(common::Error::HttpError(err));
19860                }
19861                Ok(res) => {
19862                    let (mut parts, body) = res.into_parts();
19863                    let mut body = common::Body::new(body);
19864                    if !parts.status.is_success() {
19865                        let bytes = common::to_bytes(body).await.unwrap_or_default();
19866                        let error = serde_json::from_str(&common::to_string(&bytes));
19867                        let response = common::to_response(parts, bytes.into());
19868
19869                        if let common::Retry::After(d) =
19870                            dlg.http_failure(&response, error.as_ref().ok())
19871                        {
19872                            sleep(d).await;
19873                            continue;
19874                        }
19875
19876                        dlg.finished(false);
19877
19878                        return Err(match error {
19879                            Ok(value) => common::Error::BadRequest(value),
19880                            _ => common::Error::Failure(response),
19881                        });
19882                    }
19883                    let response = {
19884                        let bytes = common::to_bytes(body).await.unwrap_or_default();
19885                        let encoded = common::to_string(&bytes);
19886                        match serde_json::from_str(&encoded) {
19887                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
19888                            Err(error) => {
19889                                dlg.response_json_decode_error(&encoded, &error);
19890                                return Err(common::Error::JsonDecodeError(
19891                                    encoded.to_string(),
19892                                    error,
19893                                ));
19894                            }
19895                        }
19896                    };
19897
19898                    dlg.finished(true);
19899                    return Ok(response);
19900                }
19901            }
19902        }
19903    }
19904
19905    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
19906    ///
19907    /// Sets the *user id* path property to the given value.
19908    ///
19909    /// Even though the property as already been set when instantiating this call,
19910    /// we provide this method for API completeness.
19911    pub fn user_id(mut self, new_value: &str) -> UserSettingSendASmimeInfoGetCall<'a, C> {
19912        self._user_id = new_value.to_string();
19913        self
19914    }
19915    /// The email address that appears in the "From:" header for mail sent using this alias.
19916    ///
19917    /// Sets the *send as email* path property to the given value.
19918    ///
19919    /// Even though the property as already been set when instantiating this call,
19920    /// we provide this method for API completeness.
19921    pub fn send_as_email(mut self, new_value: &str) -> UserSettingSendASmimeInfoGetCall<'a, C> {
19922        self._send_as_email = new_value.to_string();
19923        self
19924    }
19925    /// The immutable ID for the SmimeInfo.
19926    ///
19927    /// Sets the *id* path property to the given value.
19928    ///
19929    /// Even though the property as already been set when instantiating this call,
19930    /// we provide this method for API completeness.
19931    pub fn id(mut self, new_value: &str) -> UserSettingSendASmimeInfoGetCall<'a, C> {
19932        self._id = new_value.to_string();
19933        self
19934    }
19935    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
19936    /// while executing the actual API request.
19937    ///
19938    /// ````text
19939    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
19940    /// ````
19941    ///
19942    /// Sets the *delegate* property to the given value.
19943    pub fn delegate(
19944        mut self,
19945        new_value: &'a mut dyn common::Delegate,
19946    ) -> UserSettingSendASmimeInfoGetCall<'a, C> {
19947        self._delegate = Some(new_value);
19948        self
19949    }
19950
19951    /// Set any additional parameter of the query string used in the request.
19952    /// It should be used to set parameters which are not yet available through their own
19953    /// setters.
19954    ///
19955    /// Please note that this method must not be used to set any of the known parameters
19956    /// which have their own setter method. If done anyway, the request will fail.
19957    ///
19958    /// # Additional Parameters
19959    ///
19960    /// * *$.xgafv* (query-string) - V1 error format.
19961    /// * *access_token* (query-string) - OAuth access token.
19962    /// * *alt* (query-string) - Data format for response.
19963    /// * *callback* (query-string) - JSONP
19964    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
19965    /// * *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.
19966    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
19967    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
19968    /// * *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.
19969    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
19970    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
19971    pub fn param<T>(mut self, name: T, value: T) -> UserSettingSendASmimeInfoGetCall<'a, C>
19972    where
19973        T: AsRef<str>,
19974    {
19975        self._additional_params
19976            .insert(name.as_ref().to_string(), value.as_ref().to_string());
19977        self
19978    }
19979
19980    /// Identifies the authorization scope for the method you are building.
19981    ///
19982    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
19983    /// [`Scope::Readonly`].
19984    ///
19985    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
19986    /// tokens for more than one scope.
19987    ///
19988    /// Usually there is more than one suitable scope to authorize an operation, some of which may
19989    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
19990    /// sufficient, a read-write scope will do as well.
19991    pub fn add_scope<St>(mut self, scope: St) -> UserSettingSendASmimeInfoGetCall<'a, C>
19992    where
19993        St: AsRef<str>,
19994    {
19995        self._scopes.insert(String::from(scope.as_ref()));
19996        self
19997    }
19998    /// Identifies the authorization scope(s) for the method you are building.
19999    ///
20000    /// See [`Self::add_scope()`] for details.
20001    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingSendASmimeInfoGetCall<'a, C>
20002    where
20003        I: IntoIterator<Item = St>,
20004        St: AsRef<str>,
20005    {
20006        self._scopes
20007            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
20008        self
20009    }
20010
20011    /// Removes all scopes, and no default scope will be used either.
20012    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
20013    /// for details).
20014    pub fn clear_scopes(mut self) -> UserSettingSendASmimeInfoGetCall<'a, C> {
20015        self._scopes.clear();
20016        self
20017    }
20018}
20019
20020/// Insert (upload) the given S/MIME config for the specified send-as alias. Note that pkcs12 format is required for the key.
20021///
20022/// A builder for the *settings.sendAs.smimeInfo.insert* method supported by a *user* resource.
20023/// It is not used directly, but through a [`UserMethods`] instance.
20024///
20025/// # Example
20026///
20027/// Instantiate a resource method builder
20028///
20029/// ```test_harness,no_run
20030/// # extern crate hyper;
20031/// # extern crate hyper_rustls;
20032/// # extern crate google_gmail1 as gmail1;
20033/// use gmail1::api::SmimeInfo;
20034/// # async fn dox() {
20035/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
20036///
20037/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
20038/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
20039/// #     secret,
20040/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
20041/// # ).build().await.unwrap();
20042///
20043/// # let client = hyper_util::client::legacy::Client::builder(
20044/// #     hyper_util::rt::TokioExecutor::new()
20045/// # )
20046/// # .build(
20047/// #     hyper_rustls::HttpsConnectorBuilder::new()
20048/// #         .with_native_roots()
20049/// #         .unwrap()
20050/// #         .https_or_http()
20051/// #         .enable_http1()
20052/// #         .build()
20053/// # );
20054/// # let mut hub = Gmail::new(client, auth);
20055/// // As the method needs a request, you would usually fill it with the desired information
20056/// // into the respective structure. Some of the parts shown here might not be applicable !
20057/// // Values shown here are possibly random and not representative !
20058/// let mut req = SmimeInfo::default();
20059///
20060/// // You can configure optional parameters by calling the respective setters at will, and
20061/// // execute the final call using `doit()`.
20062/// // Values shown here are possibly random and not representative !
20063/// let result = hub.users().settings_send_as_smime_info_insert(req, "userId", "sendAsEmail")
20064///              .doit().await;
20065/// # }
20066/// ```
20067pub struct UserSettingSendASmimeInfoInsertCall<'a, C>
20068where
20069    C: 'a,
20070{
20071    hub: &'a Gmail<C>,
20072    _request: SmimeInfo,
20073    _user_id: String,
20074    _send_as_email: String,
20075    _delegate: Option<&'a mut dyn common::Delegate>,
20076    _additional_params: HashMap<String, String>,
20077    _scopes: BTreeSet<String>,
20078}
20079
20080impl<'a, C> common::CallBuilder for UserSettingSendASmimeInfoInsertCall<'a, C> {}
20081
20082impl<'a, C> UserSettingSendASmimeInfoInsertCall<'a, C>
20083where
20084    C: common::Connector,
20085{
20086    /// Perform the operation you have build so far.
20087    pub async fn doit(mut self) -> common::Result<(common::Response, SmimeInfo)> {
20088        use std::borrow::Cow;
20089        use std::io::{Read, Seek};
20090
20091        use common::{url::Params, ToParts};
20092        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
20093
20094        let mut dd = common::DefaultDelegate;
20095        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
20096        dlg.begin(common::MethodInfo {
20097            id: "gmail.users.settings.sendAs.smimeInfo.insert",
20098            http_method: hyper::Method::POST,
20099        });
20100
20101        for &field in ["alt", "userId", "sendAsEmail"].iter() {
20102            if self._additional_params.contains_key(field) {
20103                dlg.finished(false);
20104                return Err(common::Error::FieldClash(field));
20105            }
20106        }
20107
20108        let mut params = Params::with_capacity(5 + self._additional_params.len());
20109        params.push("userId", self._user_id);
20110        params.push("sendAsEmail", self._send_as_email);
20111
20112        params.extend(self._additional_params.iter());
20113
20114        params.push("alt", "json");
20115        let mut url = self.hub._base_url.clone()
20116            + "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo";
20117        if self._scopes.is_empty() {
20118            self._scopes
20119                .insert(Scope::SettingBasic.as_ref().to_string());
20120        }
20121
20122        #[allow(clippy::single_element_loop)]
20123        for &(find_this, param_name) in
20124            [("{userId}", "userId"), ("{sendAsEmail}", "sendAsEmail")].iter()
20125        {
20126            url = params.uri_replacement(url, param_name, find_this, false);
20127        }
20128        {
20129            let to_remove = ["sendAsEmail", "userId"];
20130            params.remove_params(&to_remove);
20131        }
20132
20133        let url = params.parse_with_url(&url);
20134
20135        let mut json_mime_type = mime::APPLICATION_JSON;
20136        let mut request_value_reader = {
20137            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
20138            common::remove_json_null_values(&mut value);
20139            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
20140            serde_json::to_writer(&mut dst, &value).unwrap();
20141            dst
20142        };
20143        let request_size = request_value_reader
20144            .seek(std::io::SeekFrom::End(0))
20145            .unwrap();
20146        request_value_reader
20147            .seek(std::io::SeekFrom::Start(0))
20148            .unwrap();
20149
20150        loop {
20151            let token = match self
20152                .hub
20153                .auth
20154                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
20155                .await
20156            {
20157                Ok(token) => token,
20158                Err(e) => match dlg.token(e) {
20159                    Ok(token) => token,
20160                    Err(e) => {
20161                        dlg.finished(false);
20162                        return Err(common::Error::MissingToken(e));
20163                    }
20164                },
20165            };
20166            request_value_reader
20167                .seek(std::io::SeekFrom::Start(0))
20168                .unwrap();
20169            let mut req_result = {
20170                let client = &self.hub.client;
20171                dlg.pre_request();
20172                let mut req_builder = hyper::Request::builder()
20173                    .method(hyper::Method::POST)
20174                    .uri(url.as_str())
20175                    .header(USER_AGENT, self.hub._user_agent.clone());
20176
20177                if let Some(token) = token.as_ref() {
20178                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
20179                }
20180
20181                let request = req_builder
20182                    .header(CONTENT_TYPE, json_mime_type.to_string())
20183                    .header(CONTENT_LENGTH, request_size as u64)
20184                    .body(common::to_body(
20185                        request_value_reader.get_ref().clone().into(),
20186                    ));
20187
20188                client.request(request.unwrap()).await
20189            };
20190
20191            match req_result {
20192                Err(err) => {
20193                    if let common::Retry::After(d) = dlg.http_error(&err) {
20194                        sleep(d).await;
20195                        continue;
20196                    }
20197                    dlg.finished(false);
20198                    return Err(common::Error::HttpError(err));
20199                }
20200                Ok(res) => {
20201                    let (mut parts, body) = res.into_parts();
20202                    let mut body = common::Body::new(body);
20203                    if !parts.status.is_success() {
20204                        let bytes = common::to_bytes(body).await.unwrap_or_default();
20205                        let error = serde_json::from_str(&common::to_string(&bytes));
20206                        let response = common::to_response(parts, bytes.into());
20207
20208                        if let common::Retry::After(d) =
20209                            dlg.http_failure(&response, error.as_ref().ok())
20210                        {
20211                            sleep(d).await;
20212                            continue;
20213                        }
20214
20215                        dlg.finished(false);
20216
20217                        return Err(match error {
20218                            Ok(value) => common::Error::BadRequest(value),
20219                            _ => common::Error::Failure(response),
20220                        });
20221                    }
20222                    let response = {
20223                        let bytes = common::to_bytes(body).await.unwrap_or_default();
20224                        let encoded = common::to_string(&bytes);
20225                        match serde_json::from_str(&encoded) {
20226                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
20227                            Err(error) => {
20228                                dlg.response_json_decode_error(&encoded, &error);
20229                                return Err(common::Error::JsonDecodeError(
20230                                    encoded.to_string(),
20231                                    error,
20232                                ));
20233                            }
20234                        }
20235                    };
20236
20237                    dlg.finished(true);
20238                    return Ok(response);
20239                }
20240            }
20241        }
20242    }
20243
20244    ///
20245    /// Sets the *request* property to the given value.
20246    ///
20247    /// Even though the property as already been set when instantiating this call,
20248    /// we provide this method for API completeness.
20249    pub fn request(mut self, new_value: SmimeInfo) -> UserSettingSendASmimeInfoInsertCall<'a, C> {
20250        self._request = new_value;
20251        self
20252    }
20253    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
20254    ///
20255    /// Sets the *user id* path property to the given value.
20256    ///
20257    /// Even though the property as already been set when instantiating this call,
20258    /// we provide this method for API completeness.
20259    pub fn user_id(mut self, new_value: &str) -> UserSettingSendASmimeInfoInsertCall<'a, C> {
20260        self._user_id = new_value.to_string();
20261        self
20262    }
20263    /// The email address that appears in the "From:" header for mail sent using this alias.
20264    ///
20265    /// Sets the *send as email* path property to the given value.
20266    ///
20267    /// Even though the property as already been set when instantiating this call,
20268    /// we provide this method for API completeness.
20269    pub fn send_as_email(mut self, new_value: &str) -> UserSettingSendASmimeInfoInsertCall<'a, C> {
20270        self._send_as_email = new_value.to_string();
20271        self
20272    }
20273    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
20274    /// while executing the actual API request.
20275    ///
20276    /// ````text
20277    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
20278    /// ````
20279    ///
20280    /// Sets the *delegate* property to the given value.
20281    pub fn delegate(
20282        mut self,
20283        new_value: &'a mut dyn common::Delegate,
20284    ) -> UserSettingSendASmimeInfoInsertCall<'a, C> {
20285        self._delegate = Some(new_value);
20286        self
20287    }
20288
20289    /// Set any additional parameter of the query string used in the request.
20290    /// It should be used to set parameters which are not yet available through their own
20291    /// setters.
20292    ///
20293    /// Please note that this method must not be used to set any of the known parameters
20294    /// which have their own setter method. If done anyway, the request will fail.
20295    ///
20296    /// # Additional Parameters
20297    ///
20298    /// * *$.xgafv* (query-string) - V1 error format.
20299    /// * *access_token* (query-string) - OAuth access token.
20300    /// * *alt* (query-string) - Data format for response.
20301    /// * *callback* (query-string) - JSONP
20302    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
20303    /// * *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.
20304    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
20305    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
20306    /// * *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.
20307    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
20308    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
20309    pub fn param<T>(mut self, name: T, value: T) -> UserSettingSendASmimeInfoInsertCall<'a, C>
20310    where
20311        T: AsRef<str>,
20312    {
20313        self._additional_params
20314            .insert(name.as_ref().to_string(), value.as_ref().to_string());
20315        self
20316    }
20317
20318    /// Identifies the authorization scope for the method you are building.
20319    ///
20320    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
20321    /// [`Scope::SettingBasic`].
20322    ///
20323    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
20324    /// tokens for more than one scope.
20325    ///
20326    /// Usually there is more than one suitable scope to authorize an operation, some of which may
20327    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
20328    /// sufficient, a read-write scope will do as well.
20329    pub fn add_scope<St>(mut self, scope: St) -> UserSettingSendASmimeInfoInsertCall<'a, C>
20330    where
20331        St: AsRef<str>,
20332    {
20333        self._scopes.insert(String::from(scope.as_ref()));
20334        self
20335    }
20336    /// Identifies the authorization scope(s) for the method you are building.
20337    ///
20338    /// See [`Self::add_scope()`] for details.
20339    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingSendASmimeInfoInsertCall<'a, C>
20340    where
20341        I: IntoIterator<Item = St>,
20342        St: AsRef<str>,
20343    {
20344        self._scopes
20345            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
20346        self
20347    }
20348
20349    /// Removes all scopes, and no default scope will be used either.
20350    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
20351    /// for details).
20352    pub fn clear_scopes(mut self) -> UserSettingSendASmimeInfoInsertCall<'a, C> {
20353        self._scopes.clear();
20354        self
20355    }
20356}
20357
20358/// Lists S/MIME configs for the specified send-as alias.
20359///
20360/// A builder for the *settings.sendAs.smimeInfo.list* method supported by a *user* resource.
20361/// It is not used directly, but through a [`UserMethods`] instance.
20362///
20363/// # Example
20364///
20365/// Instantiate a resource method builder
20366///
20367/// ```test_harness,no_run
20368/// # extern crate hyper;
20369/// # extern crate hyper_rustls;
20370/// # extern crate google_gmail1 as gmail1;
20371/// # async fn dox() {
20372/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
20373///
20374/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
20375/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
20376/// #     secret,
20377/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
20378/// # ).build().await.unwrap();
20379///
20380/// # let client = hyper_util::client::legacy::Client::builder(
20381/// #     hyper_util::rt::TokioExecutor::new()
20382/// # )
20383/// # .build(
20384/// #     hyper_rustls::HttpsConnectorBuilder::new()
20385/// #         .with_native_roots()
20386/// #         .unwrap()
20387/// #         .https_or_http()
20388/// #         .enable_http1()
20389/// #         .build()
20390/// # );
20391/// # let mut hub = Gmail::new(client, auth);
20392/// // You can configure optional parameters by calling the respective setters at will, and
20393/// // execute the final call using `doit()`.
20394/// // Values shown here are possibly random and not representative !
20395/// let result = hub.users().settings_send_as_smime_info_list("userId", "sendAsEmail")
20396///              .doit().await;
20397/// # }
20398/// ```
20399pub struct UserSettingSendASmimeInfoListCall<'a, C>
20400where
20401    C: 'a,
20402{
20403    hub: &'a Gmail<C>,
20404    _user_id: String,
20405    _send_as_email: String,
20406    _delegate: Option<&'a mut dyn common::Delegate>,
20407    _additional_params: HashMap<String, String>,
20408    _scopes: BTreeSet<String>,
20409}
20410
20411impl<'a, C> common::CallBuilder for UserSettingSendASmimeInfoListCall<'a, C> {}
20412
20413impl<'a, C> UserSettingSendASmimeInfoListCall<'a, C>
20414where
20415    C: common::Connector,
20416{
20417    /// Perform the operation you have build so far.
20418    pub async fn doit(mut self) -> common::Result<(common::Response, ListSmimeInfoResponse)> {
20419        use std::borrow::Cow;
20420        use std::io::{Read, Seek};
20421
20422        use common::{url::Params, ToParts};
20423        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
20424
20425        let mut dd = common::DefaultDelegate;
20426        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
20427        dlg.begin(common::MethodInfo {
20428            id: "gmail.users.settings.sendAs.smimeInfo.list",
20429            http_method: hyper::Method::GET,
20430        });
20431
20432        for &field in ["alt", "userId", "sendAsEmail"].iter() {
20433            if self._additional_params.contains_key(field) {
20434                dlg.finished(false);
20435                return Err(common::Error::FieldClash(field));
20436            }
20437        }
20438
20439        let mut params = Params::with_capacity(4 + self._additional_params.len());
20440        params.push("userId", self._user_id);
20441        params.push("sendAsEmail", self._send_as_email);
20442
20443        params.extend(self._additional_params.iter());
20444
20445        params.push("alt", "json");
20446        let mut url = self.hub._base_url.clone()
20447            + "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo";
20448        if self._scopes.is_empty() {
20449            self._scopes.insert(Scope::Readonly.as_ref().to_string());
20450        }
20451
20452        #[allow(clippy::single_element_loop)]
20453        for &(find_this, param_name) in
20454            [("{userId}", "userId"), ("{sendAsEmail}", "sendAsEmail")].iter()
20455        {
20456            url = params.uri_replacement(url, param_name, find_this, false);
20457        }
20458        {
20459            let to_remove = ["sendAsEmail", "userId"];
20460            params.remove_params(&to_remove);
20461        }
20462
20463        let url = params.parse_with_url(&url);
20464
20465        loop {
20466            let token = match self
20467                .hub
20468                .auth
20469                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
20470                .await
20471            {
20472                Ok(token) => token,
20473                Err(e) => match dlg.token(e) {
20474                    Ok(token) => token,
20475                    Err(e) => {
20476                        dlg.finished(false);
20477                        return Err(common::Error::MissingToken(e));
20478                    }
20479                },
20480            };
20481            let mut req_result = {
20482                let client = &self.hub.client;
20483                dlg.pre_request();
20484                let mut req_builder = hyper::Request::builder()
20485                    .method(hyper::Method::GET)
20486                    .uri(url.as_str())
20487                    .header(USER_AGENT, self.hub._user_agent.clone());
20488
20489                if let Some(token) = token.as_ref() {
20490                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
20491                }
20492
20493                let request = req_builder
20494                    .header(CONTENT_LENGTH, 0_u64)
20495                    .body(common::to_body::<String>(None));
20496
20497                client.request(request.unwrap()).await
20498            };
20499
20500            match req_result {
20501                Err(err) => {
20502                    if let common::Retry::After(d) = dlg.http_error(&err) {
20503                        sleep(d).await;
20504                        continue;
20505                    }
20506                    dlg.finished(false);
20507                    return Err(common::Error::HttpError(err));
20508                }
20509                Ok(res) => {
20510                    let (mut parts, body) = res.into_parts();
20511                    let mut body = common::Body::new(body);
20512                    if !parts.status.is_success() {
20513                        let bytes = common::to_bytes(body).await.unwrap_or_default();
20514                        let error = serde_json::from_str(&common::to_string(&bytes));
20515                        let response = common::to_response(parts, bytes.into());
20516
20517                        if let common::Retry::After(d) =
20518                            dlg.http_failure(&response, error.as_ref().ok())
20519                        {
20520                            sleep(d).await;
20521                            continue;
20522                        }
20523
20524                        dlg.finished(false);
20525
20526                        return Err(match error {
20527                            Ok(value) => common::Error::BadRequest(value),
20528                            _ => common::Error::Failure(response),
20529                        });
20530                    }
20531                    let response = {
20532                        let bytes = common::to_bytes(body).await.unwrap_or_default();
20533                        let encoded = common::to_string(&bytes);
20534                        match serde_json::from_str(&encoded) {
20535                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
20536                            Err(error) => {
20537                                dlg.response_json_decode_error(&encoded, &error);
20538                                return Err(common::Error::JsonDecodeError(
20539                                    encoded.to_string(),
20540                                    error,
20541                                ));
20542                            }
20543                        }
20544                    };
20545
20546                    dlg.finished(true);
20547                    return Ok(response);
20548                }
20549            }
20550        }
20551    }
20552
20553    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
20554    ///
20555    /// Sets the *user id* path property to the given value.
20556    ///
20557    /// Even though the property as already been set when instantiating this call,
20558    /// we provide this method for API completeness.
20559    pub fn user_id(mut self, new_value: &str) -> UserSettingSendASmimeInfoListCall<'a, C> {
20560        self._user_id = new_value.to_string();
20561        self
20562    }
20563    /// The email address that appears in the "From:" header for mail sent using this alias.
20564    ///
20565    /// Sets the *send as email* path property to the given value.
20566    ///
20567    /// Even though the property as already been set when instantiating this call,
20568    /// we provide this method for API completeness.
20569    pub fn send_as_email(mut self, new_value: &str) -> UserSettingSendASmimeInfoListCall<'a, C> {
20570        self._send_as_email = new_value.to_string();
20571        self
20572    }
20573    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
20574    /// while executing the actual API request.
20575    ///
20576    /// ````text
20577    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
20578    /// ````
20579    ///
20580    /// Sets the *delegate* property to the given value.
20581    pub fn delegate(
20582        mut self,
20583        new_value: &'a mut dyn common::Delegate,
20584    ) -> UserSettingSendASmimeInfoListCall<'a, C> {
20585        self._delegate = Some(new_value);
20586        self
20587    }
20588
20589    /// Set any additional parameter of the query string used in the request.
20590    /// It should be used to set parameters which are not yet available through their own
20591    /// setters.
20592    ///
20593    /// Please note that this method must not be used to set any of the known parameters
20594    /// which have their own setter method. If done anyway, the request will fail.
20595    ///
20596    /// # Additional Parameters
20597    ///
20598    /// * *$.xgafv* (query-string) - V1 error format.
20599    /// * *access_token* (query-string) - OAuth access token.
20600    /// * *alt* (query-string) - Data format for response.
20601    /// * *callback* (query-string) - JSONP
20602    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
20603    /// * *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.
20604    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
20605    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
20606    /// * *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.
20607    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
20608    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
20609    pub fn param<T>(mut self, name: T, value: T) -> UserSettingSendASmimeInfoListCall<'a, C>
20610    where
20611        T: AsRef<str>,
20612    {
20613        self._additional_params
20614            .insert(name.as_ref().to_string(), value.as_ref().to_string());
20615        self
20616    }
20617
20618    /// Identifies the authorization scope for the method you are building.
20619    ///
20620    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
20621    /// [`Scope::Readonly`].
20622    ///
20623    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
20624    /// tokens for more than one scope.
20625    ///
20626    /// Usually there is more than one suitable scope to authorize an operation, some of which may
20627    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
20628    /// sufficient, a read-write scope will do as well.
20629    pub fn add_scope<St>(mut self, scope: St) -> UserSettingSendASmimeInfoListCall<'a, C>
20630    where
20631        St: AsRef<str>,
20632    {
20633        self._scopes.insert(String::from(scope.as_ref()));
20634        self
20635    }
20636    /// Identifies the authorization scope(s) for the method you are building.
20637    ///
20638    /// See [`Self::add_scope()`] for details.
20639    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingSendASmimeInfoListCall<'a, C>
20640    where
20641        I: IntoIterator<Item = St>,
20642        St: AsRef<str>,
20643    {
20644        self._scopes
20645            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
20646        self
20647    }
20648
20649    /// Removes all scopes, and no default scope will be used either.
20650    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
20651    /// for details).
20652    pub fn clear_scopes(mut self) -> UserSettingSendASmimeInfoListCall<'a, C> {
20653        self._scopes.clear();
20654        self
20655    }
20656}
20657
20658/// Sets the default S/MIME config for the specified send-as alias.
20659///
20660/// A builder for the *settings.sendAs.smimeInfo.setDefault* method supported by a *user* resource.
20661/// It is not used directly, but through a [`UserMethods`] instance.
20662///
20663/// # Example
20664///
20665/// Instantiate a resource method builder
20666///
20667/// ```test_harness,no_run
20668/// # extern crate hyper;
20669/// # extern crate hyper_rustls;
20670/// # extern crate google_gmail1 as gmail1;
20671/// # async fn dox() {
20672/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
20673///
20674/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
20675/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
20676/// #     secret,
20677/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
20678/// # ).build().await.unwrap();
20679///
20680/// # let client = hyper_util::client::legacy::Client::builder(
20681/// #     hyper_util::rt::TokioExecutor::new()
20682/// # )
20683/// # .build(
20684/// #     hyper_rustls::HttpsConnectorBuilder::new()
20685/// #         .with_native_roots()
20686/// #         .unwrap()
20687/// #         .https_or_http()
20688/// #         .enable_http1()
20689/// #         .build()
20690/// # );
20691/// # let mut hub = Gmail::new(client, auth);
20692/// // You can configure optional parameters by calling the respective setters at will, and
20693/// // execute the final call using `doit()`.
20694/// // Values shown here are possibly random and not representative !
20695/// let result = hub.users().settings_send_as_smime_info_set_default("userId", "sendAsEmail", "id")
20696///              .doit().await;
20697/// # }
20698/// ```
20699pub struct UserSettingSendASmimeInfoSetDefaultCall<'a, C>
20700where
20701    C: 'a,
20702{
20703    hub: &'a Gmail<C>,
20704    _user_id: String,
20705    _send_as_email: String,
20706    _id: String,
20707    _delegate: Option<&'a mut dyn common::Delegate>,
20708    _additional_params: HashMap<String, String>,
20709    _scopes: BTreeSet<String>,
20710}
20711
20712impl<'a, C> common::CallBuilder for UserSettingSendASmimeInfoSetDefaultCall<'a, C> {}
20713
20714impl<'a, C> UserSettingSendASmimeInfoSetDefaultCall<'a, C>
20715where
20716    C: common::Connector,
20717{
20718    /// Perform the operation you have build so far.
20719    pub async fn doit(mut self) -> common::Result<common::Response> {
20720        use std::borrow::Cow;
20721        use std::io::{Read, Seek};
20722
20723        use common::{url::Params, ToParts};
20724        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
20725
20726        let mut dd = common::DefaultDelegate;
20727        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
20728        dlg.begin(common::MethodInfo {
20729            id: "gmail.users.settings.sendAs.smimeInfo.setDefault",
20730            http_method: hyper::Method::POST,
20731        });
20732
20733        for &field in ["userId", "sendAsEmail", "id"].iter() {
20734            if self._additional_params.contains_key(field) {
20735                dlg.finished(false);
20736                return Err(common::Error::FieldClash(field));
20737            }
20738        }
20739
20740        let mut params = Params::with_capacity(4 + self._additional_params.len());
20741        params.push("userId", self._user_id);
20742        params.push("sendAsEmail", self._send_as_email);
20743        params.push("id", self._id);
20744
20745        params.extend(self._additional_params.iter());
20746
20747        let mut url = self.hub._base_url.clone()
20748            + "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/smimeInfo/{id}/setDefault";
20749        if self._scopes.is_empty() {
20750            self._scopes
20751                .insert(Scope::SettingBasic.as_ref().to_string());
20752        }
20753
20754        #[allow(clippy::single_element_loop)]
20755        for &(find_this, param_name) in [
20756            ("{userId}", "userId"),
20757            ("{sendAsEmail}", "sendAsEmail"),
20758            ("{id}", "id"),
20759        ]
20760        .iter()
20761        {
20762            url = params.uri_replacement(url, param_name, find_this, false);
20763        }
20764        {
20765            let to_remove = ["id", "sendAsEmail", "userId"];
20766            params.remove_params(&to_remove);
20767        }
20768
20769        let url = params.parse_with_url(&url);
20770
20771        loop {
20772            let token = match self
20773                .hub
20774                .auth
20775                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
20776                .await
20777            {
20778                Ok(token) => token,
20779                Err(e) => match dlg.token(e) {
20780                    Ok(token) => token,
20781                    Err(e) => {
20782                        dlg.finished(false);
20783                        return Err(common::Error::MissingToken(e));
20784                    }
20785                },
20786            };
20787            let mut req_result = {
20788                let client = &self.hub.client;
20789                dlg.pre_request();
20790                let mut req_builder = hyper::Request::builder()
20791                    .method(hyper::Method::POST)
20792                    .uri(url.as_str())
20793                    .header(USER_AGENT, self.hub._user_agent.clone());
20794
20795                if let Some(token) = token.as_ref() {
20796                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
20797                }
20798
20799                let request = req_builder
20800                    .header(CONTENT_LENGTH, 0_u64)
20801                    .body(common::to_body::<String>(None));
20802
20803                client.request(request.unwrap()).await
20804            };
20805
20806            match req_result {
20807                Err(err) => {
20808                    if let common::Retry::After(d) = dlg.http_error(&err) {
20809                        sleep(d).await;
20810                        continue;
20811                    }
20812                    dlg.finished(false);
20813                    return Err(common::Error::HttpError(err));
20814                }
20815                Ok(res) => {
20816                    let (mut parts, body) = res.into_parts();
20817                    let mut body = common::Body::new(body);
20818                    if !parts.status.is_success() {
20819                        let bytes = common::to_bytes(body).await.unwrap_or_default();
20820                        let error = serde_json::from_str(&common::to_string(&bytes));
20821                        let response = common::to_response(parts, bytes.into());
20822
20823                        if let common::Retry::After(d) =
20824                            dlg.http_failure(&response, error.as_ref().ok())
20825                        {
20826                            sleep(d).await;
20827                            continue;
20828                        }
20829
20830                        dlg.finished(false);
20831
20832                        return Err(match error {
20833                            Ok(value) => common::Error::BadRequest(value),
20834                            _ => common::Error::Failure(response),
20835                        });
20836                    }
20837                    let response = common::Response::from_parts(parts, body);
20838
20839                    dlg.finished(true);
20840                    return Ok(response);
20841                }
20842            }
20843        }
20844    }
20845
20846    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
20847    ///
20848    /// Sets the *user id* path property to the given value.
20849    ///
20850    /// Even though the property as already been set when instantiating this call,
20851    /// we provide this method for API completeness.
20852    pub fn user_id(mut self, new_value: &str) -> UserSettingSendASmimeInfoSetDefaultCall<'a, C> {
20853        self._user_id = new_value.to_string();
20854        self
20855    }
20856    /// The email address that appears in the "From:" header for mail sent using this alias.
20857    ///
20858    /// Sets the *send as email* path property to the given value.
20859    ///
20860    /// Even though the property as already been set when instantiating this call,
20861    /// we provide this method for API completeness.
20862    pub fn send_as_email(
20863        mut self,
20864        new_value: &str,
20865    ) -> UserSettingSendASmimeInfoSetDefaultCall<'a, C> {
20866        self._send_as_email = new_value.to_string();
20867        self
20868    }
20869    /// The immutable ID for the SmimeInfo.
20870    ///
20871    /// Sets the *id* path property to the given value.
20872    ///
20873    /// Even though the property as already been set when instantiating this call,
20874    /// we provide this method for API completeness.
20875    pub fn id(mut self, new_value: &str) -> UserSettingSendASmimeInfoSetDefaultCall<'a, C> {
20876        self._id = new_value.to_string();
20877        self
20878    }
20879    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
20880    /// while executing the actual API request.
20881    ///
20882    /// ````text
20883    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
20884    /// ````
20885    ///
20886    /// Sets the *delegate* property to the given value.
20887    pub fn delegate(
20888        mut self,
20889        new_value: &'a mut dyn common::Delegate,
20890    ) -> UserSettingSendASmimeInfoSetDefaultCall<'a, C> {
20891        self._delegate = Some(new_value);
20892        self
20893    }
20894
20895    /// Set any additional parameter of the query string used in the request.
20896    /// It should be used to set parameters which are not yet available through their own
20897    /// setters.
20898    ///
20899    /// Please note that this method must not be used to set any of the known parameters
20900    /// which have their own setter method. If done anyway, the request will fail.
20901    ///
20902    /// # Additional Parameters
20903    ///
20904    /// * *$.xgafv* (query-string) - V1 error format.
20905    /// * *access_token* (query-string) - OAuth access token.
20906    /// * *alt* (query-string) - Data format for response.
20907    /// * *callback* (query-string) - JSONP
20908    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
20909    /// * *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.
20910    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
20911    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
20912    /// * *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.
20913    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
20914    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
20915    pub fn param<T>(mut self, name: T, value: T) -> UserSettingSendASmimeInfoSetDefaultCall<'a, C>
20916    where
20917        T: AsRef<str>,
20918    {
20919        self._additional_params
20920            .insert(name.as_ref().to_string(), value.as_ref().to_string());
20921        self
20922    }
20923
20924    /// Identifies the authorization scope for the method you are building.
20925    ///
20926    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
20927    /// [`Scope::SettingBasic`].
20928    ///
20929    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
20930    /// tokens for more than one scope.
20931    ///
20932    /// Usually there is more than one suitable scope to authorize an operation, some of which may
20933    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
20934    /// sufficient, a read-write scope will do as well.
20935    pub fn add_scope<St>(mut self, scope: St) -> UserSettingSendASmimeInfoSetDefaultCall<'a, C>
20936    where
20937        St: AsRef<str>,
20938    {
20939        self._scopes.insert(String::from(scope.as_ref()));
20940        self
20941    }
20942    /// Identifies the authorization scope(s) for the method you are building.
20943    ///
20944    /// See [`Self::add_scope()`] for details.
20945    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingSendASmimeInfoSetDefaultCall<'a, C>
20946    where
20947        I: IntoIterator<Item = St>,
20948        St: AsRef<str>,
20949    {
20950        self._scopes
20951            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
20952        self
20953    }
20954
20955    /// Removes all scopes, and no default scope will be used either.
20956    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
20957    /// for details).
20958    pub fn clear_scopes(mut self) -> UserSettingSendASmimeInfoSetDefaultCall<'a, C> {
20959        self._scopes.clear();
20960        self
20961    }
20962}
20963
20964/// Creates a custom "from" send-as alias. If an SMTP MSA is specified, Gmail will attempt to connect to the SMTP service to validate the configuration before creating the alias. If ownership verification is required for the alias, a message will be sent to the email address and the resource's verification status will be set to `pending`; otherwise, the resource will be created with verification status set to `accepted`. If a signature is provided, Gmail will sanitize the HTML before saving it with the alias. This method is only available to service account clients that have been delegated domain-wide authority.
20965///
20966/// A builder for the *settings.sendAs.create* method supported by a *user* resource.
20967/// It is not used directly, but through a [`UserMethods`] instance.
20968///
20969/// # Example
20970///
20971/// Instantiate a resource method builder
20972///
20973/// ```test_harness,no_run
20974/// # extern crate hyper;
20975/// # extern crate hyper_rustls;
20976/// # extern crate google_gmail1 as gmail1;
20977/// use gmail1::api::SendAs;
20978/// # async fn dox() {
20979/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
20980///
20981/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
20982/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
20983/// #     secret,
20984/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
20985/// # ).build().await.unwrap();
20986///
20987/// # let client = hyper_util::client::legacy::Client::builder(
20988/// #     hyper_util::rt::TokioExecutor::new()
20989/// # )
20990/// # .build(
20991/// #     hyper_rustls::HttpsConnectorBuilder::new()
20992/// #         .with_native_roots()
20993/// #         .unwrap()
20994/// #         .https_or_http()
20995/// #         .enable_http1()
20996/// #         .build()
20997/// # );
20998/// # let mut hub = Gmail::new(client, auth);
20999/// // As the method needs a request, you would usually fill it with the desired information
21000/// // into the respective structure. Some of the parts shown here might not be applicable !
21001/// // Values shown here are possibly random and not representative !
21002/// let mut req = SendAs::default();
21003///
21004/// // You can configure optional parameters by calling the respective setters at will, and
21005/// // execute the final call using `doit()`.
21006/// // Values shown here are possibly random and not representative !
21007/// let result = hub.users().settings_send_as_create(req, "userId")
21008///              .doit().await;
21009/// # }
21010/// ```
21011pub struct UserSettingSendACreateCall<'a, C>
21012where
21013    C: 'a,
21014{
21015    hub: &'a Gmail<C>,
21016    _request: SendAs,
21017    _user_id: String,
21018    _delegate: Option<&'a mut dyn common::Delegate>,
21019    _additional_params: HashMap<String, String>,
21020    _scopes: BTreeSet<String>,
21021}
21022
21023impl<'a, C> common::CallBuilder for UserSettingSendACreateCall<'a, C> {}
21024
21025impl<'a, C> UserSettingSendACreateCall<'a, C>
21026where
21027    C: common::Connector,
21028{
21029    /// Perform the operation you have build so far.
21030    pub async fn doit(mut self) -> common::Result<(common::Response, SendAs)> {
21031        use std::borrow::Cow;
21032        use std::io::{Read, Seek};
21033
21034        use common::{url::Params, ToParts};
21035        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
21036
21037        let mut dd = common::DefaultDelegate;
21038        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
21039        dlg.begin(common::MethodInfo {
21040            id: "gmail.users.settings.sendAs.create",
21041            http_method: hyper::Method::POST,
21042        });
21043
21044        for &field in ["alt", "userId"].iter() {
21045            if self._additional_params.contains_key(field) {
21046                dlg.finished(false);
21047                return Err(common::Error::FieldClash(field));
21048            }
21049        }
21050
21051        let mut params = Params::with_capacity(4 + self._additional_params.len());
21052        params.push("userId", self._user_id);
21053
21054        params.extend(self._additional_params.iter());
21055
21056        params.push("alt", "json");
21057        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/sendAs";
21058        if self._scopes.is_empty() {
21059            self._scopes
21060                .insert(Scope::SettingSharing.as_ref().to_string());
21061        }
21062
21063        #[allow(clippy::single_element_loop)]
21064        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
21065            url = params.uri_replacement(url, param_name, find_this, false);
21066        }
21067        {
21068            let to_remove = ["userId"];
21069            params.remove_params(&to_remove);
21070        }
21071
21072        let url = params.parse_with_url(&url);
21073
21074        let mut json_mime_type = mime::APPLICATION_JSON;
21075        let mut request_value_reader = {
21076            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
21077            common::remove_json_null_values(&mut value);
21078            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
21079            serde_json::to_writer(&mut dst, &value).unwrap();
21080            dst
21081        };
21082        let request_size = request_value_reader
21083            .seek(std::io::SeekFrom::End(0))
21084            .unwrap();
21085        request_value_reader
21086            .seek(std::io::SeekFrom::Start(0))
21087            .unwrap();
21088
21089        loop {
21090            let token = match self
21091                .hub
21092                .auth
21093                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
21094                .await
21095            {
21096                Ok(token) => token,
21097                Err(e) => match dlg.token(e) {
21098                    Ok(token) => token,
21099                    Err(e) => {
21100                        dlg.finished(false);
21101                        return Err(common::Error::MissingToken(e));
21102                    }
21103                },
21104            };
21105            request_value_reader
21106                .seek(std::io::SeekFrom::Start(0))
21107                .unwrap();
21108            let mut req_result = {
21109                let client = &self.hub.client;
21110                dlg.pre_request();
21111                let mut req_builder = hyper::Request::builder()
21112                    .method(hyper::Method::POST)
21113                    .uri(url.as_str())
21114                    .header(USER_AGENT, self.hub._user_agent.clone());
21115
21116                if let Some(token) = token.as_ref() {
21117                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
21118                }
21119
21120                let request = req_builder
21121                    .header(CONTENT_TYPE, json_mime_type.to_string())
21122                    .header(CONTENT_LENGTH, request_size as u64)
21123                    .body(common::to_body(
21124                        request_value_reader.get_ref().clone().into(),
21125                    ));
21126
21127                client.request(request.unwrap()).await
21128            };
21129
21130            match req_result {
21131                Err(err) => {
21132                    if let common::Retry::After(d) = dlg.http_error(&err) {
21133                        sleep(d).await;
21134                        continue;
21135                    }
21136                    dlg.finished(false);
21137                    return Err(common::Error::HttpError(err));
21138                }
21139                Ok(res) => {
21140                    let (mut parts, body) = res.into_parts();
21141                    let mut body = common::Body::new(body);
21142                    if !parts.status.is_success() {
21143                        let bytes = common::to_bytes(body).await.unwrap_or_default();
21144                        let error = serde_json::from_str(&common::to_string(&bytes));
21145                        let response = common::to_response(parts, bytes.into());
21146
21147                        if let common::Retry::After(d) =
21148                            dlg.http_failure(&response, error.as_ref().ok())
21149                        {
21150                            sleep(d).await;
21151                            continue;
21152                        }
21153
21154                        dlg.finished(false);
21155
21156                        return Err(match error {
21157                            Ok(value) => common::Error::BadRequest(value),
21158                            _ => common::Error::Failure(response),
21159                        });
21160                    }
21161                    let response = {
21162                        let bytes = common::to_bytes(body).await.unwrap_or_default();
21163                        let encoded = common::to_string(&bytes);
21164                        match serde_json::from_str(&encoded) {
21165                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
21166                            Err(error) => {
21167                                dlg.response_json_decode_error(&encoded, &error);
21168                                return Err(common::Error::JsonDecodeError(
21169                                    encoded.to_string(),
21170                                    error,
21171                                ));
21172                            }
21173                        }
21174                    };
21175
21176                    dlg.finished(true);
21177                    return Ok(response);
21178                }
21179            }
21180        }
21181    }
21182
21183    ///
21184    /// Sets the *request* property to the given value.
21185    ///
21186    /// Even though the property as already been set when instantiating this call,
21187    /// we provide this method for API completeness.
21188    pub fn request(mut self, new_value: SendAs) -> UserSettingSendACreateCall<'a, C> {
21189        self._request = new_value;
21190        self
21191    }
21192    /// User's email address. The special value "me" can be used to indicate the authenticated user.
21193    ///
21194    /// Sets the *user id* path property to the given value.
21195    ///
21196    /// Even though the property as already been set when instantiating this call,
21197    /// we provide this method for API completeness.
21198    pub fn user_id(mut self, new_value: &str) -> UserSettingSendACreateCall<'a, C> {
21199        self._user_id = new_value.to_string();
21200        self
21201    }
21202    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
21203    /// while executing the actual API request.
21204    ///
21205    /// ````text
21206    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
21207    /// ````
21208    ///
21209    /// Sets the *delegate* property to the given value.
21210    pub fn delegate(
21211        mut self,
21212        new_value: &'a mut dyn common::Delegate,
21213    ) -> UserSettingSendACreateCall<'a, C> {
21214        self._delegate = Some(new_value);
21215        self
21216    }
21217
21218    /// Set any additional parameter of the query string used in the request.
21219    /// It should be used to set parameters which are not yet available through their own
21220    /// setters.
21221    ///
21222    /// Please note that this method must not be used to set any of the known parameters
21223    /// which have their own setter method. If done anyway, the request will fail.
21224    ///
21225    /// # Additional Parameters
21226    ///
21227    /// * *$.xgafv* (query-string) - V1 error format.
21228    /// * *access_token* (query-string) - OAuth access token.
21229    /// * *alt* (query-string) - Data format for response.
21230    /// * *callback* (query-string) - JSONP
21231    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
21232    /// * *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.
21233    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
21234    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
21235    /// * *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.
21236    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
21237    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
21238    pub fn param<T>(mut self, name: T, value: T) -> UserSettingSendACreateCall<'a, C>
21239    where
21240        T: AsRef<str>,
21241    {
21242        self._additional_params
21243            .insert(name.as_ref().to_string(), value.as_ref().to_string());
21244        self
21245    }
21246
21247    /// Identifies the authorization scope for the method you are building.
21248    ///
21249    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
21250    /// [`Scope::SettingSharing`].
21251    ///
21252    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
21253    /// tokens for more than one scope.
21254    ///
21255    /// Usually there is more than one suitable scope to authorize an operation, some of which may
21256    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
21257    /// sufficient, a read-write scope will do as well.
21258    pub fn add_scope<St>(mut self, scope: St) -> UserSettingSendACreateCall<'a, C>
21259    where
21260        St: AsRef<str>,
21261    {
21262        self._scopes.insert(String::from(scope.as_ref()));
21263        self
21264    }
21265    /// Identifies the authorization scope(s) for the method you are building.
21266    ///
21267    /// See [`Self::add_scope()`] for details.
21268    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingSendACreateCall<'a, C>
21269    where
21270        I: IntoIterator<Item = St>,
21271        St: AsRef<str>,
21272    {
21273        self._scopes
21274            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
21275        self
21276    }
21277
21278    /// Removes all scopes, and no default scope will be used either.
21279    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
21280    /// for details).
21281    pub fn clear_scopes(mut self) -> UserSettingSendACreateCall<'a, C> {
21282        self._scopes.clear();
21283        self
21284    }
21285}
21286
21287/// Deletes the specified send-as alias. Revokes any verification that may have been required for using it. This method is only available to service account clients that have been delegated domain-wide authority.
21288///
21289/// A builder for the *settings.sendAs.delete* method supported by a *user* resource.
21290/// It is not used directly, but through a [`UserMethods`] instance.
21291///
21292/// # Example
21293///
21294/// Instantiate a resource method builder
21295///
21296/// ```test_harness,no_run
21297/// # extern crate hyper;
21298/// # extern crate hyper_rustls;
21299/// # extern crate google_gmail1 as gmail1;
21300/// # async fn dox() {
21301/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
21302///
21303/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
21304/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
21305/// #     secret,
21306/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
21307/// # ).build().await.unwrap();
21308///
21309/// # let client = hyper_util::client::legacy::Client::builder(
21310/// #     hyper_util::rt::TokioExecutor::new()
21311/// # )
21312/// # .build(
21313/// #     hyper_rustls::HttpsConnectorBuilder::new()
21314/// #         .with_native_roots()
21315/// #         .unwrap()
21316/// #         .https_or_http()
21317/// #         .enable_http1()
21318/// #         .build()
21319/// # );
21320/// # let mut hub = Gmail::new(client, auth);
21321/// // You can configure optional parameters by calling the respective setters at will, and
21322/// // execute the final call using `doit()`.
21323/// // Values shown here are possibly random and not representative !
21324/// let result = hub.users().settings_send_as_delete("userId", "sendAsEmail")
21325///              .doit().await;
21326/// # }
21327/// ```
21328pub struct UserSettingSendADeleteCall<'a, C>
21329where
21330    C: 'a,
21331{
21332    hub: &'a Gmail<C>,
21333    _user_id: String,
21334    _send_as_email: String,
21335    _delegate: Option<&'a mut dyn common::Delegate>,
21336    _additional_params: HashMap<String, String>,
21337    _scopes: BTreeSet<String>,
21338}
21339
21340impl<'a, C> common::CallBuilder for UserSettingSendADeleteCall<'a, C> {}
21341
21342impl<'a, C> UserSettingSendADeleteCall<'a, C>
21343where
21344    C: common::Connector,
21345{
21346    /// Perform the operation you have build so far.
21347    pub async fn doit(mut self) -> common::Result<common::Response> {
21348        use std::borrow::Cow;
21349        use std::io::{Read, Seek};
21350
21351        use common::{url::Params, ToParts};
21352        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
21353
21354        let mut dd = common::DefaultDelegate;
21355        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
21356        dlg.begin(common::MethodInfo {
21357            id: "gmail.users.settings.sendAs.delete",
21358            http_method: hyper::Method::DELETE,
21359        });
21360
21361        for &field in ["userId", "sendAsEmail"].iter() {
21362            if self._additional_params.contains_key(field) {
21363                dlg.finished(false);
21364                return Err(common::Error::FieldClash(field));
21365            }
21366        }
21367
21368        let mut params = Params::with_capacity(3 + self._additional_params.len());
21369        params.push("userId", self._user_id);
21370        params.push("sendAsEmail", self._send_as_email);
21371
21372        params.extend(self._additional_params.iter());
21373
21374        let mut url =
21375            self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}";
21376        if self._scopes.is_empty() {
21377            self._scopes
21378                .insert(Scope::SettingSharing.as_ref().to_string());
21379        }
21380
21381        #[allow(clippy::single_element_loop)]
21382        for &(find_this, param_name) in
21383            [("{userId}", "userId"), ("{sendAsEmail}", "sendAsEmail")].iter()
21384        {
21385            url = params.uri_replacement(url, param_name, find_this, false);
21386        }
21387        {
21388            let to_remove = ["sendAsEmail", "userId"];
21389            params.remove_params(&to_remove);
21390        }
21391
21392        let url = params.parse_with_url(&url);
21393
21394        loop {
21395            let token = match self
21396                .hub
21397                .auth
21398                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
21399                .await
21400            {
21401                Ok(token) => token,
21402                Err(e) => match dlg.token(e) {
21403                    Ok(token) => token,
21404                    Err(e) => {
21405                        dlg.finished(false);
21406                        return Err(common::Error::MissingToken(e));
21407                    }
21408                },
21409            };
21410            let mut req_result = {
21411                let client = &self.hub.client;
21412                dlg.pre_request();
21413                let mut req_builder = hyper::Request::builder()
21414                    .method(hyper::Method::DELETE)
21415                    .uri(url.as_str())
21416                    .header(USER_AGENT, self.hub._user_agent.clone());
21417
21418                if let Some(token) = token.as_ref() {
21419                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
21420                }
21421
21422                let request = req_builder
21423                    .header(CONTENT_LENGTH, 0_u64)
21424                    .body(common::to_body::<String>(None));
21425
21426                client.request(request.unwrap()).await
21427            };
21428
21429            match req_result {
21430                Err(err) => {
21431                    if let common::Retry::After(d) = dlg.http_error(&err) {
21432                        sleep(d).await;
21433                        continue;
21434                    }
21435                    dlg.finished(false);
21436                    return Err(common::Error::HttpError(err));
21437                }
21438                Ok(res) => {
21439                    let (mut parts, body) = res.into_parts();
21440                    let mut body = common::Body::new(body);
21441                    if !parts.status.is_success() {
21442                        let bytes = common::to_bytes(body).await.unwrap_or_default();
21443                        let error = serde_json::from_str(&common::to_string(&bytes));
21444                        let response = common::to_response(parts, bytes.into());
21445
21446                        if let common::Retry::After(d) =
21447                            dlg.http_failure(&response, error.as_ref().ok())
21448                        {
21449                            sleep(d).await;
21450                            continue;
21451                        }
21452
21453                        dlg.finished(false);
21454
21455                        return Err(match error {
21456                            Ok(value) => common::Error::BadRequest(value),
21457                            _ => common::Error::Failure(response),
21458                        });
21459                    }
21460                    let response = common::Response::from_parts(parts, body);
21461
21462                    dlg.finished(true);
21463                    return Ok(response);
21464                }
21465            }
21466        }
21467    }
21468
21469    /// User's email address. The special value "me" can be used to indicate the authenticated user.
21470    ///
21471    /// Sets the *user id* path property to the given value.
21472    ///
21473    /// Even though the property as already been set when instantiating this call,
21474    /// we provide this method for API completeness.
21475    pub fn user_id(mut self, new_value: &str) -> UserSettingSendADeleteCall<'a, C> {
21476        self._user_id = new_value.to_string();
21477        self
21478    }
21479    /// The send-as alias to be deleted.
21480    ///
21481    /// Sets the *send as email* path property to the given value.
21482    ///
21483    /// Even though the property as already been set when instantiating this call,
21484    /// we provide this method for API completeness.
21485    pub fn send_as_email(mut self, new_value: &str) -> UserSettingSendADeleteCall<'a, C> {
21486        self._send_as_email = new_value.to_string();
21487        self
21488    }
21489    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
21490    /// while executing the actual API request.
21491    ///
21492    /// ````text
21493    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
21494    /// ````
21495    ///
21496    /// Sets the *delegate* property to the given value.
21497    pub fn delegate(
21498        mut self,
21499        new_value: &'a mut dyn common::Delegate,
21500    ) -> UserSettingSendADeleteCall<'a, C> {
21501        self._delegate = Some(new_value);
21502        self
21503    }
21504
21505    /// Set any additional parameter of the query string used in the request.
21506    /// It should be used to set parameters which are not yet available through their own
21507    /// setters.
21508    ///
21509    /// Please note that this method must not be used to set any of the known parameters
21510    /// which have their own setter method. If done anyway, the request will fail.
21511    ///
21512    /// # Additional Parameters
21513    ///
21514    /// * *$.xgafv* (query-string) - V1 error format.
21515    /// * *access_token* (query-string) - OAuth access token.
21516    /// * *alt* (query-string) - Data format for response.
21517    /// * *callback* (query-string) - JSONP
21518    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
21519    /// * *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.
21520    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
21521    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
21522    /// * *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.
21523    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
21524    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
21525    pub fn param<T>(mut self, name: T, value: T) -> UserSettingSendADeleteCall<'a, C>
21526    where
21527        T: AsRef<str>,
21528    {
21529        self._additional_params
21530            .insert(name.as_ref().to_string(), value.as_ref().to_string());
21531        self
21532    }
21533
21534    /// Identifies the authorization scope for the method you are building.
21535    ///
21536    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
21537    /// [`Scope::SettingSharing`].
21538    ///
21539    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
21540    /// tokens for more than one scope.
21541    ///
21542    /// Usually there is more than one suitable scope to authorize an operation, some of which may
21543    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
21544    /// sufficient, a read-write scope will do as well.
21545    pub fn add_scope<St>(mut self, scope: St) -> UserSettingSendADeleteCall<'a, C>
21546    where
21547        St: AsRef<str>,
21548    {
21549        self._scopes.insert(String::from(scope.as_ref()));
21550        self
21551    }
21552    /// Identifies the authorization scope(s) for the method you are building.
21553    ///
21554    /// See [`Self::add_scope()`] for details.
21555    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingSendADeleteCall<'a, C>
21556    where
21557        I: IntoIterator<Item = St>,
21558        St: AsRef<str>,
21559    {
21560        self._scopes
21561            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
21562        self
21563    }
21564
21565    /// Removes all scopes, and no default scope will be used either.
21566    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
21567    /// for details).
21568    pub fn clear_scopes(mut self) -> UserSettingSendADeleteCall<'a, C> {
21569        self._scopes.clear();
21570        self
21571    }
21572}
21573
21574/// Gets the specified send-as alias. Fails with an HTTP 404 error if the specified address is not a member of the collection.
21575///
21576/// A builder for the *settings.sendAs.get* method supported by a *user* resource.
21577/// It is not used directly, but through a [`UserMethods`] instance.
21578///
21579/// # Example
21580///
21581/// Instantiate a resource method builder
21582///
21583/// ```test_harness,no_run
21584/// # extern crate hyper;
21585/// # extern crate hyper_rustls;
21586/// # extern crate google_gmail1 as gmail1;
21587/// # async fn dox() {
21588/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
21589///
21590/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
21591/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
21592/// #     secret,
21593/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
21594/// # ).build().await.unwrap();
21595///
21596/// # let client = hyper_util::client::legacy::Client::builder(
21597/// #     hyper_util::rt::TokioExecutor::new()
21598/// # )
21599/// # .build(
21600/// #     hyper_rustls::HttpsConnectorBuilder::new()
21601/// #         .with_native_roots()
21602/// #         .unwrap()
21603/// #         .https_or_http()
21604/// #         .enable_http1()
21605/// #         .build()
21606/// # );
21607/// # let mut hub = Gmail::new(client, auth);
21608/// // You can configure optional parameters by calling the respective setters at will, and
21609/// // execute the final call using `doit()`.
21610/// // Values shown here are possibly random and not representative !
21611/// let result = hub.users().settings_send_as_get("userId", "sendAsEmail")
21612///              .doit().await;
21613/// # }
21614/// ```
21615pub struct UserSettingSendAGetCall<'a, C>
21616where
21617    C: 'a,
21618{
21619    hub: &'a Gmail<C>,
21620    _user_id: String,
21621    _send_as_email: String,
21622    _delegate: Option<&'a mut dyn common::Delegate>,
21623    _additional_params: HashMap<String, String>,
21624    _scopes: BTreeSet<String>,
21625}
21626
21627impl<'a, C> common::CallBuilder for UserSettingSendAGetCall<'a, C> {}
21628
21629impl<'a, C> UserSettingSendAGetCall<'a, C>
21630where
21631    C: common::Connector,
21632{
21633    /// Perform the operation you have build so far.
21634    pub async fn doit(mut self) -> common::Result<(common::Response, SendAs)> {
21635        use std::borrow::Cow;
21636        use std::io::{Read, Seek};
21637
21638        use common::{url::Params, ToParts};
21639        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
21640
21641        let mut dd = common::DefaultDelegate;
21642        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
21643        dlg.begin(common::MethodInfo {
21644            id: "gmail.users.settings.sendAs.get",
21645            http_method: hyper::Method::GET,
21646        });
21647
21648        for &field in ["alt", "userId", "sendAsEmail"].iter() {
21649            if self._additional_params.contains_key(field) {
21650                dlg.finished(false);
21651                return Err(common::Error::FieldClash(field));
21652            }
21653        }
21654
21655        let mut params = Params::with_capacity(4 + self._additional_params.len());
21656        params.push("userId", self._user_id);
21657        params.push("sendAsEmail", self._send_as_email);
21658
21659        params.extend(self._additional_params.iter());
21660
21661        params.push("alt", "json");
21662        let mut url =
21663            self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}";
21664        if self._scopes.is_empty() {
21665            self._scopes.insert(Scope::Readonly.as_ref().to_string());
21666        }
21667
21668        #[allow(clippy::single_element_loop)]
21669        for &(find_this, param_name) in
21670            [("{userId}", "userId"), ("{sendAsEmail}", "sendAsEmail")].iter()
21671        {
21672            url = params.uri_replacement(url, param_name, find_this, false);
21673        }
21674        {
21675            let to_remove = ["sendAsEmail", "userId"];
21676            params.remove_params(&to_remove);
21677        }
21678
21679        let url = params.parse_with_url(&url);
21680
21681        loop {
21682            let token = match self
21683                .hub
21684                .auth
21685                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
21686                .await
21687            {
21688                Ok(token) => token,
21689                Err(e) => match dlg.token(e) {
21690                    Ok(token) => token,
21691                    Err(e) => {
21692                        dlg.finished(false);
21693                        return Err(common::Error::MissingToken(e));
21694                    }
21695                },
21696            };
21697            let mut req_result = {
21698                let client = &self.hub.client;
21699                dlg.pre_request();
21700                let mut req_builder = hyper::Request::builder()
21701                    .method(hyper::Method::GET)
21702                    .uri(url.as_str())
21703                    .header(USER_AGENT, self.hub._user_agent.clone());
21704
21705                if let Some(token) = token.as_ref() {
21706                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
21707                }
21708
21709                let request = req_builder
21710                    .header(CONTENT_LENGTH, 0_u64)
21711                    .body(common::to_body::<String>(None));
21712
21713                client.request(request.unwrap()).await
21714            };
21715
21716            match req_result {
21717                Err(err) => {
21718                    if let common::Retry::After(d) = dlg.http_error(&err) {
21719                        sleep(d).await;
21720                        continue;
21721                    }
21722                    dlg.finished(false);
21723                    return Err(common::Error::HttpError(err));
21724                }
21725                Ok(res) => {
21726                    let (mut parts, body) = res.into_parts();
21727                    let mut body = common::Body::new(body);
21728                    if !parts.status.is_success() {
21729                        let bytes = common::to_bytes(body).await.unwrap_or_default();
21730                        let error = serde_json::from_str(&common::to_string(&bytes));
21731                        let response = common::to_response(parts, bytes.into());
21732
21733                        if let common::Retry::After(d) =
21734                            dlg.http_failure(&response, error.as_ref().ok())
21735                        {
21736                            sleep(d).await;
21737                            continue;
21738                        }
21739
21740                        dlg.finished(false);
21741
21742                        return Err(match error {
21743                            Ok(value) => common::Error::BadRequest(value),
21744                            _ => common::Error::Failure(response),
21745                        });
21746                    }
21747                    let response = {
21748                        let bytes = common::to_bytes(body).await.unwrap_or_default();
21749                        let encoded = common::to_string(&bytes);
21750                        match serde_json::from_str(&encoded) {
21751                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
21752                            Err(error) => {
21753                                dlg.response_json_decode_error(&encoded, &error);
21754                                return Err(common::Error::JsonDecodeError(
21755                                    encoded.to_string(),
21756                                    error,
21757                                ));
21758                            }
21759                        }
21760                    };
21761
21762                    dlg.finished(true);
21763                    return Ok(response);
21764                }
21765            }
21766        }
21767    }
21768
21769    /// User's email address. The special value "me" can be used to indicate the authenticated user.
21770    ///
21771    /// Sets the *user id* path property to the given value.
21772    ///
21773    /// Even though the property as already been set when instantiating this call,
21774    /// we provide this method for API completeness.
21775    pub fn user_id(mut self, new_value: &str) -> UserSettingSendAGetCall<'a, C> {
21776        self._user_id = new_value.to_string();
21777        self
21778    }
21779    /// The send-as alias to be retrieved.
21780    ///
21781    /// Sets the *send as email* path property to the given value.
21782    ///
21783    /// Even though the property as already been set when instantiating this call,
21784    /// we provide this method for API completeness.
21785    pub fn send_as_email(mut self, new_value: &str) -> UserSettingSendAGetCall<'a, C> {
21786        self._send_as_email = new_value.to_string();
21787        self
21788    }
21789    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
21790    /// while executing the actual API request.
21791    ///
21792    /// ````text
21793    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
21794    /// ````
21795    ///
21796    /// Sets the *delegate* property to the given value.
21797    pub fn delegate(
21798        mut self,
21799        new_value: &'a mut dyn common::Delegate,
21800    ) -> UserSettingSendAGetCall<'a, C> {
21801        self._delegate = Some(new_value);
21802        self
21803    }
21804
21805    /// Set any additional parameter of the query string used in the request.
21806    /// It should be used to set parameters which are not yet available through their own
21807    /// setters.
21808    ///
21809    /// Please note that this method must not be used to set any of the known parameters
21810    /// which have their own setter method. If done anyway, the request will fail.
21811    ///
21812    /// # Additional Parameters
21813    ///
21814    /// * *$.xgafv* (query-string) - V1 error format.
21815    /// * *access_token* (query-string) - OAuth access token.
21816    /// * *alt* (query-string) - Data format for response.
21817    /// * *callback* (query-string) - JSONP
21818    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
21819    /// * *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.
21820    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
21821    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
21822    /// * *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.
21823    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
21824    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
21825    pub fn param<T>(mut self, name: T, value: T) -> UserSettingSendAGetCall<'a, C>
21826    where
21827        T: AsRef<str>,
21828    {
21829        self._additional_params
21830            .insert(name.as_ref().to_string(), value.as_ref().to_string());
21831        self
21832    }
21833
21834    /// Identifies the authorization scope for the method you are building.
21835    ///
21836    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
21837    /// [`Scope::Readonly`].
21838    ///
21839    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
21840    /// tokens for more than one scope.
21841    ///
21842    /// Usually there is more than one suitable scope to authorize an operation, some of which may
21843    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
21844    /// sufficient, a read-write scope will do as well.
21845    pub fn add_scope<St>(mut self, scope: St) -> UserSettingSendAGetCall<'a, C>
21846    where
21847        St: AsRef<str>,
21848    {
21849        self._scopes.insert(String::from(scope.as_ref()));
21850        self
21851    }
21852    /// Identifies the authorization scope(s) for the method you are building.
21853    ///
21854    /// See [`Self::add_scope()`] for details.
21855    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingSendAGetCall<'a, C>
21856    where
21857        I: IntoIterator<Item = St>,
21858        St: AsRef<str>,
21859    {
21860        self._scopes
21861            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
21862        self
21863    }
21864
21865    /// Removes all scopes, and no default scope will be used either.
21866    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
21867    /// for details).
21868    pub fn clear_scopes(mut self) -> UserSettingSendAGetCall<'a, C> {
21869        self._scopes.clear();
21870        self
21871    }
21872}
21873
21874/// Lists the send-as aliases for the specified account. The result includes the primary send-as address associated with the account as well as any custom "from" aliases.
21875///
21876/// A builder for the *settings.sendAs.list* method supported by a *user* resource.
21877/// It is not used directly, but through a [`UserMethods`] instance.
21878///
21879/// # Example
21880///
21881/// Instantiate a resource method builder
21882///
21883/// ```test_harness,no_run
21884/// # extern crate hyper;
21885/// # extern crate hyper_rustls;
21886/// # extern crate google_gmail1 as gmail1;
21887/// # async fn dox() {
21888/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
21889///
21890/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
21891/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
21892/// #     secret,
21893/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
21894/// # ).build().await.unwrap();
21895///
21896/// # let client = hyper_util::client::legacy::Client::builder(
21897/// #     hyper_util::rt::TokioExecutor::new()
21898/// # )
21899/// # .build(
21900/// #     hyper_rustls::HttpsConnectorBuilder::new()
21901/// #         .with_native_roots()
21902/// #         .unwrap()
21903/// #         .https_or_http()
21904/// #         .enable_http1()
21905/// #         .build()
21906/// # );
21907/// # let mut hub = Gmail::new(client, auth);
21908/// // You can configure optional parameters by calling the respective setters at will, and
21909/// // execute the final call using `doit()`.
21910/// // Values shown here are possibly random and not representative !
21911/// let result = hub.users().settings_send_as_list("userId")
21912///              .doit().await;
21913/// # }
21914/// ```
21915pub struct UserSettingSendAListCall<'a, C>
21916where
21917    C: 'a,
21918{
21919    hub: &'a Gmail<C>,
21920    _user_id: String,
21921    _delegate: Option<&'a mut dyn common::Delegate>,
21922    _additional_params: HashMap<String, String>,
21923    _scopes: BTreeSet<String>,
21924}
21925
21926impl<'a, C> common::CallBuilder for UserSettingSendAListCall<'a, C> {}
21927
21928impl<'a, C> UserSettingSendAListCall<'a, C>
21929where
21930    C: common::Connector,
21931{
21932    /// Perform the operation you have build so far.
21933    pub async fn doit(mut self) -> common::Result<(common::Response, ListSendAsResponse)> {
21934        use std::borrow::Cow;
21935        use std::io::{Read, Seek};
21936
21937        use common::{url::Params, ToParts};
21938        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
21939
21940        let mut dd = common::DefaultDelegate;
21941        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
21942        dlg.begin(common::MethodInfo {
21943            id: "gmail.users.settings.sendAs.list",
21944            http_method: hyper::Method::GET,
21945        });
21946
21947        for &field in ["alt", "userId"].iter() {
21948            if self._additional_params.contains_key(field) {
21949                dlg.finished(false);
21950                return Err(common::Error::FieldClash(field));
21951            }
21952        }
21953
21954        let mut params = Params::with_capacity(3 + self._additional_params.len());
21955        params.push("userId", self._user_id);
21956
21957        params.extend(self._additional_params.iter());
21958
21959        params.push("alt", "json");
21960        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/sendAs";
21961        if self._scopes.is_empty() {
21962            self._scopes.insert(Scope::Readonly.as_ref().to_string());
21963        }
21964
21965        #[allow(clippy::single_element_loop)]
21966        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
21967            url = params.uri_replacement(url, param_name, find_this, false);
21968        }
21969        {
21970            let to_remove = ["userId"];
21971            params.remove_params(&to_remove);
21972        }
21973
21974        let url = params.parse_with_url(&url);
21975
21976        loop {
21977            let token = match self
21978                .hub
21979                .auth
21980                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
21981                .await
21982            {
21983                Ok(token) => token,
21984                Err(e) => match dlg.token(e) {
21985                    Ok(token) => token,
21986                    Err(e) => {
21987                        dlg.finished(false);
21988                        return Err(common::Error::MissingToken(e));
21989                    }
21990                },
21991            };
21992            let mut req_result = {
21993                let client = &self.hub.client;
21994                dlg.pre_request();
21995                let mut req_builder = hyper::Request::builder()
21996                    .method(hyper::Method::GET)
21997                    .uri(url.as_str())
21998                    .header(USER_AGENT, self.hub._user_agent.clone());
21999
22000                if let Some(token) = token.as_ref() {
22001                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
22002                }
22003
22004                let request = req_builder
22005                    .header(CONTENT_LENGTH, 0_u64)
22006                    .body(common::to_body::<String>(None));
22007
22008                client.request(request.unwrap()).await
22009            };
22010
22011            match req_result {
22012                Err(err) => {
22013                    if let common::Retry::After(d) = dlg.http_error(&err) {
22014                        sleep(d).await;
22015                        continue;
22016                    }
22017                    dlg.finished(false);
22018                    return Err(common::Error::HttpError(err));
22019                }
22020                Ok(res) => {
22021                    let (mut parts, body) = res.into_parts();
22022                    let mut body = common::Body::new(body);
22023                    if !parts.status.is_success() {
22024                        let bytes = common::to_bytes(body).await.unwrap_or_default();
22025                        let error = serde_json::from_str(&common::to_string(&bytes));
22026                        let response = common::to_response(parts, bytes.into());
22027
22028                        if let common::Retry::After(d) =
22029                            dlg.http_failure(&response, error.as_ref().ok())
22030                        {
22031                            sleep(d).await;
22032                            continue;
22033                        }
22034
22035                        dlg.finished(false);
22036
22037                        return Err(match error {
22038                            Ok(value) => common::Error::BadRequest(value),
22039                            _ => common::Error::Failure(response),
22040                        });
22041                    }
22042                    let response = {
22043                        let bytes = common::to_bytes(body).await.unwrap_or_default();
22044                        let encoded = common::to_string(&bytes);
22045                        match serde_json::from_str(&encoded) {
22046                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
22047                            Err(error) => {
22048                                dlg.response_json_decode_error(&encoded, &error);
22049                                return Err(common::Error::JsonDecodeError(
22050                                    encoded.to_string(),
22051                                    error,
22052                                ));
22053                            }
22054                        }
22055                    };
22056
22057                    dlg.finished(true);
22058                    return Ok(response);
22059                }
22060            }
22061        }
22062    }
22063
22064    /// User's email address. The special value "me" can be used to indicate the authenticated user.
22065    ///
22066    /// Sets the *user id* path property to the given value.
22067    ///
22068    /// Even though the property as already been set when instantiating this call,
22069    /// we provide this method for API completeness.
22070    pub fn user_id(mut self, new_value: &str) -> UserSettingSendAListCall<'a, C> {
22071        self._user_id = new_value.to_string();
22072        self
22073    }
22074    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
22075    /// while executing the actual API request.
22076    ///
22077    /// ````text
22078    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
22079    /// ````
22080    ///
22081    /// Sets the *delegate* property to the given value.
22082    pub fn delegate(
22083        mut self,
22084        new_value: &'a mut dyn common::Delegate,
22085    ) -> UserSettingSendAListCall<'a, C> {
22086        self._delegate = Some(new_value);
22087        self
22088    }
22089
22090    /// Set any additional parameter of the query string used in the request.
22091    /// It should be used to set parameters which are not yet available through their own
22092    /// setters.
22093    ///
22094    /// Please note that this method must not be used to set any of the known parameters
22095    /// which have their own setter method. If done anyway, the request will fail.
22096    ///
22097    /// # Additional Parameters
22098    ///
22099    /// * *$.xgafv* (query-string) - V1 error format.
22100    /// * *access_token* (query-string) - OAuth access token.
22101    /// * *alt* (query-string) - Data format for response.
22102    /// * *callback* (query-string) - JSONP
22103    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
22104    /// * *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.
22105    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
22106    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
22107    /// * *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.
22108    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
22109    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
22110    pub fn param<T>(mut self, name: T, value: T) -> UserSettingSendAListCall<'a, C>
22111    where
22112        T: AsRef<str>,
22113    {
22114        self._additional_params
22115            .insert(name.as_ref().to_string(), value.as_ref().to_string());
22116        self
22117    }
22118
22119    /// Identifies the authorization scope for the method you are building.
22120    ///
22121    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
22122    /// [`Scope::Readonly`].
22123    ///
22124    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
22125    /// tokens for more than one scope.
22126    ///
22127    /// Usually there is more than one suitable scope to authorize an operation, some of which may
22128    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
22129    /// sufficient, a read-write scope will do as well.
22130    pub fn add_scope<St>(mut self, scope: St) -> UserSettingSendAListCall<'a, C>
22131    where
22132        St: AsRef<str>,
22133    {
22134        self._scopes.insert(String::from(scope.as_ref()));
22135        self
22136    }
22137    /// Identifies the authorization scope(s) for the method you are building.
22138    ///
22139    /// See [`Self::add_scope()`] for details.
22140    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingSendAListCall<'a, C>
22141    where
22142        I: IntoIterator<Item = St>,
22143        St: AsRef<str>,
22144    {
22145        self._scopes
22146            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
22147        self
22148    }
22149
22150    /// Removes all scopes, and no default scope will be used either.
22151    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
22152    /// for details).
22153    pub fn clear_scopes(mut self) -> UserSettingSendAListCall<'a, C> {
22154        self._scopes.clear();
22155        self
22156    }
22157}
22158
22159/// Patch the specified send-as alias.
22160///
22161/// A builder for the *settings.sendAs.patch* method supported by a *user* resource.
22162/// It is not used directly, but through a [`UserMethods`] instance.
22163///
22164/// # Example
22165///
22166/// Instantiate a resource method builder
22167///
22168/// ```test_harness,no_run
22169/// # extern crate hyper;
22170/// # extern crate hyper_rustls;
22171/// # extern crate google_gmail1 as gmail1;
22172/// use gmail1::api::SendAs;
22173/// # async fn dox() {
22174/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
22175///
22176/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
22177/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
22178/// #     secret,
22179/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
22180/// # ).build().await.unwrap();
22181///
22182/// # let client = hyper_util::client::legacy::Client::builder(
22183/// #     hyper_util::rt::TokioExecutor::new()
22184/// # )
22185/// # .build(
22186/// #     hyper_rustls::HttpsConnectorBuilder::new()
22187/// #         .with_native_roots()
22188/// #         .unwrap()
22189/// #         .https_or_http()
22190/// #         .enable_http1()
22191/// #         .build()
22192/// # );
22193/// # let mut hub = Gmail::new(client, auth);
22194/// // As the method needs a request, you would usually fill it with the desired information
22195/// // into the respective structure. Some of the parts shown here might not be applicable !
22196/// // Values shown here are possibly random and not representative !
22197/// let mut req = SendAs::default();
22198///
22199/// // You can configure optional parameters by calling the respective setters at will, and
22200/// // execute the final call using `doit()`.
22201/// // Values shown here are possibly random and not representative !
22202/// let result = hub.users().settings_send_as_patch(req, "userId", "sendAsEmail")
22203///              .doit().await;
22204/// # }
22205/// ```
22206pub struct UserSettingSendAPatchCall<'a, C>
22207where
22208    C: 'a,
22209{
22210    hub: &'a Gmail<C>,
22211    _request: SendAs,
22212    _user_id: String,
22213    _send_as_email: String,
22214    _delegate: Option<&'a mut dyn common::Delegate>,
22215    _additional_params: HashMap<String, String>,
22216    _scopes: BTreeSet<String>,
22217}
22218
22219impl<'a, C> common::CallBuilder for UserSettingSendAPatchCall<'a, C> {}
22220
22221impl<'a, C> UserSettingSendAPatchCall<'a, C>
22222where
22223    C: common::Connector,
22224{
22225    /// Perform the operation you have build so far.
22226    pub async fn doit(mut self) -> common::Result<(common::Response, SendAs)> {
22227        use std::borrow::Cow;
22228        use std::io::{Read, Seek};
22229
22230        use common::{url::Params, ToParts};
22231        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
22232
22233        let mut dd = common::DefaultDelegate;
22234        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
22235        dlg.begin(common::MethodInfo {
22236            id: "gmail.users.settings.sendAs.patch",
22237            http_method: hyper::Method::PATCH,
22238        });
22239
22240        for &field in ["alt", "userId", "sendAsEmail"].iter() {
22241            if self._additional_params.contains_key(field) {
22242                dlg.finished(false);
22243                return Err(common::Error::FieldClash(field));
22244            }
22245        }
22246
22247        let mut params = Params::with_capacity(5 + self._additional_params.len());
22248        params.push("userId", self._user_id);
22249        params.push("sendAsEmail", self._send_as_email);
22250
22251        params.extend(self._additional_params.iter());
22252
22253        params.push("alt", "json");
22254        let mut url =
22255            self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}";
22256        if self._scopes.is_empty() {
22257            self._scopes
22258                .insert(Scope::SettingBasic.as_ref().to_string());
22259        }
22260
22261        #[allow(clippy::single_element_loop)]
22262        for &(find_this, param_name) in
22263            [("{userId}", "userId"), ("{sendAsEmail}", "sendAsEmail")].iter()
22264        {
22265            url = params.uri_replacement(url, param_name, find_this, false);
22266        }
22267        {
22268            let to_remove = ["sendAsEmail", "userId"];
22269            params.remove_params(&to_remove);
22270        }
22271
22272        let url = params.parse_with_url(&url);
22273
22274        let mut json_mime_type = mime::APPLICATION_JSON;
22275        let mut request_value_reader = {
22276            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
22277            common::remove_json_null_values(&mut value);
22278            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
22279            serde_json::to_writer(&mut dst, &value).unwrap();
22280            dst
22281        };
22282        let request_size = request_value_reader
22283            .seek(std::io::SeekFrom::End(0))
22284            .unwrap();
22285        request_value_reader
22286            .seek(std::io::SeekFrom::Start(0))
22287            .unwrap();
22288
22289        loop {
22290            let token = match self
22291                .hub
22292                .auth
22293                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
22294                .await
22295            {
22296                Ok(token) => token,
22297                Err(e) => match dlg.token(e) {
22298                    Ok(token) => token,
22299                    Err(e) => {
22300                        dlg.finished(false);
22301                        return Err(common::Error::MissingToken(e));
22302                    }
22303                },
22304            };
22305            request_value_reader
22306                .seek(std::io::SeekFrom::Start(0))
22307                .unwrap();
22308            let mut req_result = {
22309                let client = &self.hub.client;
22310                dlg.pre_request();
22311                let mut req_builder = hyper::Request::builder()
22312                    .method(hyper::Method::PATCH)
22313                    .uri(url.as_str())
22314                    .header(USER_AGENT, self.hub._user_agent.clone());
22315
22316                if let Some(token) = token.as_ref() {
22317                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
22318                }
22319
22320                let request = req_builder
22321                    .header(CONTENT_TYPE, json_mime_type.to_string())
22322                    .header(CONTENT_LENGTH, request_size as u64)
22323                    .body(common::to_body(
22324                        request_value_reader.get_ref().clone().into(),
22325                    ));
22326
22327                client.request(request.unwrap()).await
22328            };
22329
22330            match req_result {
22331                Err(err) => {
22332                    if let common::Retry::After(d) = dlg.http_error(&err) {
22333                        sleep(d).await;
22334                        continue;
22335                    }
22336                    dlg.finished(false);
22337                    return Err(common::Error::HttpError(err));
22338                }
22339                Ok(res) => {
22340                    let (mut parts, body) = res.into_parts();
22341                    let mut body = common::Body::new(body);
22342                    if !parts.status.is_success() {
22343                        let bytes = common::to_bytes(body).await.unwrap_or_default();
22344                        let error = serde_json::from_str(&common::to_string(&bytes));
22345                        let response = common::to_response(parts, bytes.into());
22346
22347                        if let common::Retry::After(d) =
22348                            dlg.http_failure(&response, error.as_ref().ok())
22349                        {
22350                            sleep(d).await;
22351                            continue;
22352                        }
22353
22354                        dlg.finished(false);
22355
22356                        return Err(match error {
22357                            Ok(value) => common::Error::BadRequest(value),
22358                            _ => common::Error::Failure(response),
22359                        });
22360                    }
22361                    let response = {
22362                        let bytes = common::to_bytes(body).await.unwrap_or_default();
22363                        let encoded = common::to_string(&bytes);
22364                        match serde_json::from_str(&encoded) {
22365                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
22366                            Err(error) => {
22367                                dlg.response_json_decode_error(&encoded, &error);
22368                                return Err(common::Error::JsonDecodeError(
22369                                    encoded.to_string(),
22370                                    error,
22371                                ));
22372                            }
22373                        }
22374                    };
22375
22376                    dlg.finished(true);
22377                    return Ok(response);
22378                }
22379            }
22380        }
22381    }
22382
22383    ///
22384    /// Sets the *request* property to the given value.
22385    ///
22386    /// Even though the property as already been set when instantiating this call,
22387    /// we provide this method for API completeness.
22388    pub fn request(mut self, new_value: SendAs) -> UserSettingSendAPatchCall<'a, C> {
22389        self._request = new_value;
22390        self
22391    }
22392    /// User's email address. The special value "me" can be used to indicate the authenticated user.
22393    ///
22394    /// Sets the *user id* path property to the given value.
22395    ///
22396    /// Even though the property as already been set when instantiating this call,
22397    /// we provide this method for API completeness.
22398    pub fn user_id(mut self, new_value: &str) -> UserSettingSendAPatchCall<'a, C> {
22399        self._user_id = new_value.to_string();
22400        self
22401    }
22402    /// The send-as alias to be updated.
22403    ///
22404    /// Sets the *send as email* path property to the given value.
22405    ///
22406    /// Even though the property as already been set when instantiating this call,
22407    /// we provide this method for API completeness.
22408    pub fn send_as_email(mut self, new_value: &str) -> UserSettingSendAPatchCall<'a, C> {
22409        self._send_as_email = new_value.to_string();
22410        self
22411    }
22412    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
22413    /// while executing the actual API request.
22414    ///
22415    /// ````text
22416    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
22417    /// ````
22418    ///
22419    /// Sets the *delegate* property to the given value.
22420    pub fn delegate(
22421        mut self,
22422        new_value: &'a mut dyn common::Delegate,
22423    ) -> UserSettingSendAPatchCall<'a, C> {
22424        self._delegate = Some(new_value);
22425        self
22426    }
22427
22428    /// Set any additional parameter of the query string used in the request.
22429    /// It should be used to set parameters which are not yet available through their own
22430    /// setters.
22431    ///
22432    /// Please note that this method must not be used to set any of the known parameters
22433    /// which have their own setter method. If done anyway, the request will fail.
22434    ///
22435    /// # Additional Parameters
22436    ///
22437    /// * *$.xgafv* (query-string) - V1 error format.
22438    /// * *access_token* (query-string) - OAuth access token.
22439    /// * *alt* (query-string) - Data format for response.
22440    /// * *callback* (query-string) - JSONP
22441    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
22442    /// * *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.
22443    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
22444    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
22445    /// * *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.
22446    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
22447    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
22448    pub fn param<T>(mut self, name: T, value: T) -> UserSettingSendAPatchCall<'a, C>
22449    where
22450        T: AsRef<str>,
22451    {
22452        self._additional_params
22453            .insert(name.as_ref().to_string(), value.as_ref().to_string());
22454        self
22455    }
22456
22457    /// Identifies the authorization scope for the method you are building.
22458    ///
22459    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
22460    /// [`Scope::SettingBasic`].
22461    ///
22462    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
22463    /// tokens for more than one scope.
22464    ///
22465    /// Usually there is more than one suitable scope to authorize an operation, some of which may
22466    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
22467    /// sufficient, a read-write scope will do as well.
22468    pub fn add_scope<St>(mut self, scope: St) -> UserSettingSendAPatchCall<'a, C>
22469    where
22470        St: AsRef<str>,
22471    {
22472        self._scopes.insert(String::from(scope.as_ref()));
22473        self
22474    }
22475    /// Identifies the authorization scope(s) for the method you are building.
22476    ///
22477    /// See [`Self::add_scope()`] for details.
22478    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingSendAPatchCall<'a, C>
22479    where
22480        I: IntoIterator<Item = St>,
22481        St: AsRef<str>,
22482    {
22483        self._scopes
22484            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
22485        self
22486    }
22487
22488    /// Removes all scopes, and no default scope will be used either.
22489    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
22490    /// for details).
22491    pub fn clear_scopes(mut self) -> UserSettingSendAPatchCall<'a, C> {
22492        self._scopes.clear();
22493        self
22494    }
22495}
22496
22497/// Updates a send-as alias. If a signature is provided, Gmail will sanitize the HTML before saving it with the alias. Addresses other than the primary address for the account can only be updated by service account clients that have been delegated domain-wide authority.
22498///
22499/// A builder for the *settings.sendAs.update* method supported by a *user* resource.
22500/// It is not used directly, but through a [`UserMethods`] instance.
22501///
22502/// # Example
22503///
22504/// Instantiate a resource method builder
22505///
22506/// ```test_harness,no_run
22507/// # extern crate hyper;
22508/// # extern crate hyper_rustls;
22509/// # extern crate google_gmail1 as gmail1;
22510/// use gmail1::api::SendAs;
22511/// # async fn dox() {
22512/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
22513///
22514/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
22515/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
22516/// #     secret,
22517/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
22518/// # ).build().await.unwrap();
22519///
22520/// # let client = hyper_util::client::legacy::Client::builder(
22521/// #     hyper_util::rt::TokioExecutor::new()
22522/// # )
22523/// # .build(
22524/// #     hyper_rustls::HttpsConnectorBuilder::new()
22525/// #         .with_native_roots()
22526/// #         .unwrap()
22527/// #         .https_or_http()
22528/// #         .enable_http1()
22529/// #         .build()
22530/// # );
22531/// # let mut hub = Gmail::new(client, auth);
22532/// // As the method needs a request, you would usually fill it with the desired information
22533/// // into the respective structure. Some of the parts shown here might not be applicable !
22534/// // Values shown here are possibly random and not representative !
22535/// let mut req = SendAs::default();
22536///
22537/// // You can configure optional parameters by calling the respective setters at will, and
22538/// // execute the final call using `doit()`.
22539/// // Values shown here are possibly random and not representative !
22540/// let result = hub.users().settings_send_as_update(req, "userId", "sendAsEmail")
22541///              .doit().await;
22542/// # }
22543/// ```
22544pub struct UserSettingSendAUpdateCall<'a, C>
22545where
22546    C: 'a,
22547{
22548    hub: &'a Gmail<C>,
22549    _request: SendAs,
22550    _user_id: String,
22551    _send_as_email: String,
22552    _delegate: Option<&'a mut dyn common::Delegate>,
22553    _additional_params: HashMap<String, String>,
22554    _scopes: BTreeSet<String>,
22555}
22556
22557impl<'a, C> common::CallBuilder for UserSettingSendAUpdateCall<'a, C> {}
22558
22559impl<'a, C> UserSettingSendAUpdateCall<'a, C>
22560where
22561    C: common::Connector,
22562{
22563    /// Perform the operation you have build so far.
22564    pub async fn doit(mut self) -> common::Result<(common::Response, SendAs)> {
22565        use std::borrow::Cow;
22566        use std::io::{Read, Seek};
22567
22568        use common::{url::Params, ToParts};
22569        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
22570
22571        let mut dd = common::DefaultDelegate;
22572        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
22573        dlg.begin(common::MethodInfo {
22574            id: "gmail.users.settings.sendAs.update",
22575            http_method: hyper::Method::PUT,
22576        });
22577
22578        for &field in ["alt", "userId", "sendAsEmail"].iter() {
22579            if self._additional_params.contains_key(field) {
22580                dlg.finished(false);
22581                return Err(common::Error::FieldClash(field));
22582            }
22583        }
22584
22585        let mut params = Params::with_capacity(5 + self._additional_params.len());
22586        params.push("userId", self._user_id);
22587        params.push("sendAsEmail", self._send_as_email);
22588
22589        params.extend(self._additional_params.iter());
22590
22591        params.push("alt", "json");
22592        let mut url =
22593            self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}";
22594        if self._scopes.is_empty() {
22595            self._scopes
22596                .insert(Scope::SettingBasic.as_ref().to_string());
22597        }
22598
22599        #[allow(clippy::single_element_loop)]
22600        for &(find_this, param_name) in
22601            [("{userId}", "userId"), ("{sendAsEmail}", "sendAsEmail")].iter()
22602        {
22603            url = params.uri_replacement(url, param_name, find_this, false);
22604        }
22605        {
22606            let to_remove = ["sendAsEmail", "userId"];
22607            params.remove_params(&to_remove);
22608        }
22609
22610        let url = params.parse_with_url(&url);
22611
22612        let mut json_mime_type = mime::APPLICATION_JSON;
22613        let mut request_value_reader = {
22614            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
22615            common::remove_json_null_values(&mut value);
22616            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
22617            serde_json::to_writer(&mut dst, &value).unwrap();
22618            dst
22619        };
22620        let request_size = request_value_reader
22621            .seek(std::io::SeekFrom::End(0))
22622            .unwrap();
22623        request_value_reader
22624            .seek(std::io::SeekFrom::Start(0))
22625            .unwrap();
22626
22627        loop {
22628            let token = match self
22629                .hub
22630                .auth
22631                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
22632                .await
22633            {
22634                Ok(token) => token,
22635                Err(e) => match dlg.token(e) {
22636                    Ok(token) => token,
22637                    Err(e) => {
22638                        dlg.finished(false);
22639                        return Err(common::Error::MissingToken(e));
22640                    }
22641                },
22642            };
22643            request_value_reader
22644                .seek(std::io::SeekFrom::Start(0))
22645                .unwrap();
22646            let mut req_result = {
22647                let client = &self.hub.client;
22648                dlg.pre_request();
22649                let mut req_builder = hyper::Request::builder()
22650                    .method(hyper::Method::PUT)
22651                    .uri(url.as_str())
22652                    .header(USER_AGENT, self.hub._user_agent.clone());
22653
22654                if let Some(token) = token.as_ref() {
22655                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
22656                }
22657
22658                let request = req_builder
22659                    .header(CONTENT_TYPE, json_mime_type.to_string())
22660                    .header(CONTENT_LENGTH, request_size as u64)
22661                    .body(common::to_body(
22662                        request_value_reader.get_ref().clone().into(),
22663                    ));
22664
22665                client.request(request.unwrap()).await
22666            };
22667
22668            match req_result {
22669                Err(err) => {
22670                    if let common::Retry::After(d) = dlg.http_error(&err) {
22671                        sleep(d).await;
22672                        continue;
22673                    }
22674                    dlg.finished(false);
22675                    return Err(common::Error::HttpError(err));
22676                }
22677                Ok(res) => {
22678                    let (mut parts, body) = res.into_parts();
22679                    let mut body = common::Body::new(body);
22680                    if !parts.status.is_success() {
22681                        let bytes = common::to_bytes(body).await.unwrap_or_default();
22682                        let error = serde_json::from_str(&common::to_string(&bytes));
22683                        let response = common::to_response(parts, bytes.into());
22684
22685                        if let common::Retry::After(d) =
22686                            dlg.http_failure(&response, error.as_ref().ok())
22687                        {
22688                            sleep(d).await;
22689                            continue;
22690                        }
22691
22692                        dlg.finished(false);
22693
22694                        return Err(match error {
22695                            Ok(value) => common::Error::BadRequest(value),
22696                            _ => common::Error::Failure(response),
22697                        });
22698                    }
22699                    let response = {
22700                        let bytes = common::to_bytes(body).await.unwrap_or_default();
22701                        let encoded = common::to_string(&bytes);
22702                        match serde_json::from_str(&encoded) {
22703                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
22704                            Err(error) => {
22705                                dlg.response_json_decode_error(&encoded, &error);
22706                                return Err(common::Error::JsonDecodeError(
22707                                    encoded.to_string(),
22708                                    error,
22709                                ));
22710                            }
22711                        }
22712                    };
22713
22714                    dlg.finished(true);
22715                    return Ok(response);
22716                }
22717            }
22718        }
22719    }
22720
22721    ///
22722    /// Sets the *request* property to the given value.
22723    ///
22724    /// Even though the property as already been set when instantiating this call,
22725    /// we provide this method for API completeness.
22726    pub fn request(mut self, new_value: SendAs) -> UserSettingSendAUpdateCall<'a, C> {
22727        self._request = new_value;
22728        self
22729    }
22730    /// User's email address. The special value "me" can be used to indicate the authenticated user.
22731    ///
22732    /// Sets the *user id* path property to the given value.
22733    ///
22734    /// Even though the property as already been set when instantiating this call,
22735    /// we provide this method for API completeness.
22736    pub fn user_id(mut self, new_value: &str) -> UserSettingSendAUpdateCall<'a, C> {
22737        self._user_id = new_value.to_string();
22738        self
22739    }
22740    /// The send-as alias to be updated.
22741    ///
22742    /// Sets the *send as email* path property to the given value.
22743    ///
22744    /// Even though the property as already been set when instantiating this call,
22745    /// we provide this method for API completeness.
22746    pub fn send_as_email(mut self, new_value: &str) -> UserSettingSendAUpdateCall<'a, C> {
22747        self._send_as_email = new_value.to_string();
22748        self
22749    }
22750    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
22751    /// while executing the actual API request.
22752    ///
22753    /// ````text
22754    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
22755    /// ````
22756    ///
22757    /// Sets the *delegate* property to the given value.
22758    pub fn delegate(
22759        mut self,
22760        new_value: &'a mut dyn common::Delegate,
22761    ) -> UserSettingSendAUpdateCall<'a, C> {
22762        self._delegate = Some(new_value);
22763        self
22764    }
22765
22766    /// Set any additional parameter of the query string used in the request.
22767    /// It should be used to set parameters which are not yet available through their own
22768    /// setters.
22769    ///
22770    /// Please note that this method must not be used to set any of the known parameters
22771    /// which have their own setter method. If done anyway, the request will fail.
22772    ///
22773    /// # Additional Parameters
22774    ///
22775    /// * *$.xgafv* (query-string) - V1 error format.
22776    /// * *access_token* (query-string) - OAuth access token.
22777    /// * *alt* (query-string) - Data format for response.
22778    /// * *callback* (query-string) - JSONP
22779    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
22780    /// * *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.
22781    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
22782    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
22783    /// * *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.
22784    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
22785    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
22786    pub fn param<T>(mut self, name: T, value: T) -> UserSettingSendAUpdateCall<'a, C>
22787    where
22788        T: AsRef<str>,
22789    {
22790        self._additional_params
22791            .insert(name.as_ref().to_string(), value.as_ref().to_string());
22792        self
22793    }
22794
22795    /// Identifies the authorization scope for the method you are building.
22796    ///
22797    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
22798    /// [`Scope::SettingBasic`].
22799    ///
22800    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
22801    /// tokens for more than one scope.
22802    ///
22803    /// Usually there is more than one suitable scope to authorize an operation, some of which may
22804    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
22805    /// sufficient, a read-write scope will do as well.
22806    pub fn add_scope<St>(mut self, scope: St) -> UserSettingSendAUpdateCall<'a, C>
22807    where
22808        St: AsRef<str>,
22809    {
22810        self._scopes.insert(String::from(scope.as_ref()));
22811        self
22812    }
22813    /// Identifies the authorization scope(s) for the method you are building.
22814    ///
22815    /// See [`Self::add_scope()`] for details.
22816    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingSendAUpdateCall<'a, C>
22817    where
22818        I: IntoIterator<Item = St>,
22819        St: AsRef<str>,
22820    {
22821        self._scopes
22822            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
22823        self
22824    }
22825
22826    /// Removes all scopes, and no default scope will be used either.
22827    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
22828    /// for details).
22829    pub fn clear_scopes(mut self) -> UserSettingSendAUpdateCall<'a, C> {
22830        self._scopes.clear();
22831        self
22832    }
22833}
22834
22835/// Sends a verification email to the specified send-as alias address. The verification status must be `pending`. This method is only available to service account clients that have been delegated domain-wide authority.
22836///
22837/// A builder for the *settings.sendAs.verify* method supported by a *user* resource.
22838/// It is not used directly, but through a [`UserMethods`] instance.
22839///
22840/// # Example
22841///
22842/// Instantiate a resource method builder
22843///
22844/// ```test_harness,no_run
22845/// # extern crate hyper;
22846/// # extern crate hyper_rustls;
22847/// # extern crate google_gmail1 as gmail1;
22848/// # async fn dox() {
22849/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
22850///
22851/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
22852/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
22853/// #     secret,
22854/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
22855/// # ).build().await.unwrap();
22856///
22857/// # let client = hyper_util::client::legacy::Client::builder(
22858/// #     hyper_util::rt::TokioExecutor::new()
22859/// # )
22860/// # .build(
22861/// #     hyper_rustls::HttpsConnectorBuilder::new()
22862/// #         .with_native_roots()
22863/// #         .unwrap()
22864/// #         .https_or_http()
22865/// #         .enable_http1()
22866/// #         .build()
22867/// # );
22868/// # let mut hub = Gmail::new(client, auth);
22869/// // You can configure optional parameters by calling the respective setters at will, and
22870/// // execute the final call using `doit()`.
22871/// // Values shown here are possibly random and not representative !
22872/// let result = hub.users().settings_send_as_verify("userId", "sendAsEmail")
22873///              .doit().await;
22874/// # }
22875/// ```
22876pub struct UserSettingSendAVerifyCall<'a, C>
22877where
22878    C: 'a,
22879{
22880    hub: &'a Gmail<C>,
22881    _user_id: String,
22882    _send_as_email: String,
22883    _delegate: Option<&'a mut dyn common::Delegate>,
22884    _additional_params: HashMap<String, String>,
22885    _scopes: BTreeSet<String>,
22886}
22887
22888impl<'a, C> common::CallBuilder for UserSettingSendAVerifyCall<'a, C> {}
22889
22890impl<'a, C> UserSettingSendAVerifyCall<'a, C>
22891where
22892    C: common::Connector,
22893{
22894    /// Perform the operation you have build so far.
22895    pub async fn doit(mut self) -> common::Result<common::Response> {
22896        use std::borrow::Cow;
22897        use std::io::{Read, Seek};
22898
22899        use common::{url::Params, ToParts};
22900        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
22901
22902        let mut dd = common::DefaultDelegate;
22903        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
22904        dlg.begin(common::MethodInfo {
22905            id: "gmail.users.settings.sendAs.verify",
22906            http_method: hyper::Method::POST,
22907        });
22908
22909        for &field in ["userId", "sendAsEmail"].iter() {
22910            if self._additional_params.contains_key(field) {
22911                dlg.finished(false);
22912                return Err(common::Error::FieldClash(field));
22913            }
22914        }
22915
22916        let mut params = Params::with_capacity(3 + self._additional_params.len());
22917        params.push("userId", self._user_id);
22918        params.push("sendAsEmail", self._send_as_email);
22919
22920        params.extend(self._additional_params.iter());
22921
22922        let mut url = self.hub._base_url.clone()
22923            + "gmail/v1/users/{userId}/settings/sendAs/{sendAsEmail}/verify";
22924        if self._scopes.is_empty() {
22925            self._scopes
22926                .insert(Scope::SettingSharing.as_ref().to_string());
22927        }
22928
22929        #[allow(clippy::single_element_loop)]
22930        for &(find_this, param_name) in
22931            [("{userId}", "userId"), ("{sendAsEmail}", "sendAsEmail")].iter()
22932        {
22933            url = params.uri_replacement(url, param_name, find_this, false);
22934        }
22935        {
22936            let to_remove = ["sendAsEmail", "userId"];
22937            params.remove_params(&to_remove);
22938        }
22939
22940        let url = params.parse_with_url(&url);
22941
22942        loop {
22943            let token = match self
22944                .hub
22945                .auth
22946                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
22947                .await
22948            {
22949                Ok(token) => token,
22950                Err(e) => match dlg.token(e) {
22951                    Ok(token) => token,
22952                    Err(e) => {
22953                        dlg.finished(false);
22954                        return Err(common::Error::MissingToken(e));
22955                    }
22956                },
22957            };
22958            let mut req_result = {
22959                let client = &self.hub.client;
22960                dlg.pre_request();
22961                let mut req_builder = hyper::Request::builder()
22962                    .method(hyper::Method::POST)
22963                    .uri(url.as_str())
22964                    .header(USER_AGENT, self.hub._user_agent.clone());
22965
22966                if let Some(token) = token.as_ref() {
22967                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
22968                }
22969
22970                let request = req_builder
22971                    .header(CONTENT_LENGTH, 0_u64)
22972                    .body(common::to_body::<String>(None));
22973
22974                client.request(request.unwrap()).await
22975            };
22976
22977            match req_result {
22978                Err(err) => {
22979                    if let common::Retry::After(d) = dlg.http_error(&err) {
22980                        sleep(d).await;
22981                        continue;
22982                    }
22983                    dlg.finished(false);
22984                    return Err(common::Error::HttpError(err));
22985                }
22986                Ok(res) => {
22987                    let (mut parts, body) = res.into_parts();
22988                    let mut body = common::Body::new(body);
22989                    if !parts.status.is_success() {
22990                        let bytes = common::to_bytes(body).await.unwrap_or_default();
22991                        let error = serde_json::from_str(&common::to_string(&bytes));
22992                        let response = common::to_response(parts, bytes.into());
22993
22994                        if let common::Retry::After(d) =
22995                            dlg.http_failure(&response, error.as_ref().ok())
22996                        {
22997                            sleep(d).await;
22998                            continue;
22999                        }
23000
23001                        dlg.finished(false);
23002
23003                        return Err(match error {
23004                            Ok(value) => common::Error::BadRequest(value),
23005                            _ => common::Error::Failure(response),
23006                        });
23007                    }
23008                    let response = common::Response::from_parts(parts, body);
23009
23010                    dlg.finished(true);
23011                    return Ok(response);
23012                }
23013            }
23014        }
23015    }
23016
23017    /// User's email address. The special value "me" can be used to indicate the authenticated user.
23018    ///
23019    /// Sets the *user id* path property to the given value.
23020    ///
23021    /// Even though the property as already been set when instantiating this call,
23022    /// we provide this method for API completeness.
23023    pub fn user_id(mut self, new_value: &str) -> UserSettingSendAVerifyCall<'a, C> {
23024        self._user_id = new_value.to_string();
23025        self
23026    }
23027    /// The send-as alias to be verified.
23028    ///
23029    /// Sets the *send as email* path property to the given value.
23030    ///
23031    /// Even though the property as already been set when instantiating this call,
23032    /// we provide this method for API completeness.
23033    pub fn send_as_email(mut self, new_value: &str) -> UserSettingSendAVerifyCall<'a, C> {
23034        self._send_as_email = new_value.to_string();
23035        self
23036    }
23037    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
23038    /// while executing the actual API request.
23039    ///
23040    /// ````text
23041    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
23042    /// ````
23043    ///
23044    /// Sets the *delegate* property to the given value.
23045    pub fn delegate(
23046        mut self,
23047        new_value: &'a mut dyn common::Delegate,
23048    ) -> UserSettingSendAVerifyCall<'a, C> {
23049        self._delegate = Some(new_value);
23050        self
23051    }
23052
23053    /// Set any additional parameter of the query string used in the request.
23054    /// It should be used to set parameters which are not yet available through their own
23055    /// setters.
23056    ///
23057    /// Please note that this method must not be used to set any of the known parameters
23058    /// which have their own setter method. If done anyway, the request will fail.
23059    ///
23060    /// # Additional Parameters
23061    ///
23062    /// * *$.xgafv* (query-string) - V1 error format.
23063    /// * *access_token* (query-string) - OAuth access token.
23064    /// * *alt* (query-string) - Data format for response.
23065    /// * *callback* (query-string) - JSONP
23066    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
23067    /// * *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.
23068    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
23069    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
23070    /// * *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.
23071    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
23072    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
23073    pub fn param<T>(mut self, name: T, value: T) -> UserSettingSendAVerifyCall<'a, C>
23074    where
23075        T: AsRef<str>,
23076    {
23077        self._additional_params
23078            .insert(name.as_ref().to_string(), value.as_ref().to_string());
23079        self
23080    }
23081
23082    /// Identifies the authorization scope for the method you are building.
23083    ///
23084    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
23085    /// [`Scope::SettingSharing`].
23086    ///
23087    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
23088    /// tokens for more than one scope.
23089    ///
23090    /// Usually there is more than one suitable scope to authorize an operation, some of which may
23091    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
23092    /// sufficient, a read-write scope will do as well.
23093    pub fn add_scope<St>(mut self, scope: St) -> UserSettingSendAVerifyCall<'a, C>
23094    where
23095        St: AsRef<str>,
23096    {
23097        self._scopes.insert(String::from(scope.as_ref()));
23098        self
23099    }
23100    /// Identifies the authorization scope(s) for the method you are building.
23101    ///
23102    /// See [`Self::add_scope()`] for details.
23103    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingSendAVerifyCall<'a, C>
23104    where
23105        I: IntoIterator<Item = St>,
23106        St: AsRef<str>,
23107    {
23108        self._scopes
23109            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
23110        self
23111    }
23112
23113    /// Removes all scopes, and no default scope will be used either.
23114    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
23115    /// for details).
23116    pub fn clear_scopes(mut self) -> UserSettingSendAVerifyCall<'a, C> {
23117        self._scopes.clear();
23118        self
23119    }
23120}
23121
23122/// Gets the auto-forwarding setting for the specified account.
23123///
23124/// A builder for the *settings.getAutoForwarding* method supported by a *user* resource.
23125/// It is not used directly, but through a [`UserMethods`] instance.
23126///
23127/// # Example
23128///
23129/// Instantiate a resource method builder
23130///
23131/// ```test_harness,no_run
23132/// # extern crate hyper;
23133/// # extern crate hyper_rustls;
23134/// # extern crate google_gmail1 as gmail1;
23135/// # async fn dox() {
23136/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
23137///
23138/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
23139/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
23140/// #     secret,
23141/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
23142/// # ).build().await.unwrap();
23143///
23144/// # let client = hyper_util::client::legacy::Client::builder(
23145/// #     hyper_util::rt::TokioExecutor::new()
23146/// # )
23147/// # .build(
23148/// #     hyper_rustls::HttpsConnectorBuilder::new()
23149/// #         .with_native_roots()
23150/// #         .unwrap()
23151/// #         .https_or_http()
23152/// #         .enable_http1()
23153/// #         .build()
23154/// # );
23155/// # let mut hub = Gmail::new(client, auth);
23156/// // You can configure optional parameters by calling the respective setters at will, and
23157/// // execute the final call using `doit()`.
23158/// // Values shown here are possibly random and not representative !
23159/// let result = hub.users().settings_get_auto_forwarding("userId")
23160///              .doit().await;
23161/// # }
23162/// ```
23163pub struct UserSettingGetAutoForwardingCall<'a, C>
23164where
23165    C: 'a,
23166{
23167    hub: &'a Gmail<C>,
23168    _user_id: String,
23169    _delegate: Option<&'a mut dyn common::Delegate>,
23170    _additional_params: HashMap<String, String>,
23171    _scopes: BTreeSet<String>,
23172}
23173
23174impl<'a, C> common::CallBuilder for UserSettingGetAutoForwardingCall<'a, C> {}
23175
23176impl<'a, C> UserSettingGetAutoForwardingCall<'a, C>
23177where
23178    C: common::Connector,
23179{
23180    /// Perform the operation you have build so far.
23181    pub async fn doit(mut self) -> common::Result<(common::Response, AutoForwarding)> {
23182        use std::borrow::Cow;
23183        use std::io::{Read, Seek};
23184
23185        use common::{url::Params, ToParts};
23186        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
23187
23188        let mut dd = common::DefaultDelegate;
23189        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
23190        dlg.begin(common::MethodInfo {
23191            id: "gmail.users.settings.getAutoForwarding",
23192            http_method: hyper::Method::GET,
23193        });
23194
23195        for &field in ["alt", "userId"].iter() {
23196            if self._additional_params.contains_key(field) {
23197                dlg.finished(false);
23198                return Err(common::Error::FieldClash(field));
23199            }
23200        }
23201
23202        let mut params = Params::with_capacity(3 + self._additional_params.len());
23203        params.push("userId", self._user_id);
23204
23205        params.extend(self._additional_params.iter());
23206
23207        params.push("alt", "json");
23208        let mut url =
23209            self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/autoForwarding";
23210        if self._scopes.is_empty() {
23211            self._scopes.insert(Scope::Readonly.as_ref().to_string());
23212        }
23213
23214        #[allow(clippy::single_element_loop)]
23215        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
23216            url = params.uri_replacement(url, param_name, find_this, false);
23217        }
23218        {
23219            let to_remove = ["userId"];
23220            params.remove_params(&to_remove);
23221        }
23222
23223        let url = params.parse_with_url(&url);
23224
23225        loop {
23226            let token = match self
23227                .hub
23228                .auth
23229                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
23230                .await
23231            {
23232                Ok(token) => token,
23233                Err(e) => match dlg.token(e) {
23234                    Ok(token) => token,
23235                    Err(e) => {
23236                        dlg.finished(false);
23237                        return Err(common::Error::MissingToken(e));
23238                    }
23239                },
23240            };
23241            let mut req_result = {
23242                let client = &self.hub.client;
23243                dlg.pre_request();
23244                let mut req_builder = hyper::Request::builder()
23245                    .method(hyper::Method::GET)
23246                    .uri(url.as_str())
23247                    .header(USER_AGENT, self.hub._user_agent.clone());
23248
23249                if let Some(token) = token.as_ref() {
23250                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
23251                }
23252
23253                let request = req_builder
23254                    .header(CONTENT_LENGTH, 0_u64)
23255                    .body(common::to_body::<String>(None));
23256
23257                client.request(request.unwrap()).await
23258            };
23259
23260            match req_result {
23261                Err(err) => {
23262                    if let common::Retry::After(d) = dlg.http_error(&err) {
23263                        sleep(d).await;
23264                        continue;
23265                    }
23266                    dlg.finished(false);
23267                    return Err(common::Error::HttpError(err));
23268                }
23269                Ok(res) => {
23270                    let (mut parts, body) = res.into_parts();
23271                    let mut body = common::Body::new(body);
23272                    if !parts.status.is_success() {
23273                        let bytes = common::to_bytes(body).await.unwrap_or_default();
23274                        let error = serde_json::from_str(&common::to_string(&bytes));
23275                        let response = common::to_response(parts, bytes.into());
23276
23277                        if let common::Retry::After(d) =
23278                            dlg.http_failure(&response, error.as_ref().ok())
23279                        {
23280                            sleep(d).await;
23281                            continue;
23282                        }
23283
23284                        dlg.finished(false);
23285
23286                        return Err(match error {
23287                            Ok(value) => common::Error::BadRequest(value),
23288                            _ => common::Error::Failure(response),
23289                        });
23290                    }
23291                    let response = {
23292                        let bytes = common::to_bytes(body).await.unwrap_or_default();
23293                        let encoded = common::to_string(&bytes);
23294                        match serde_json::from_str(&encoded) {
23295                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
23296                            Err(error) => {
23297                                dlg.response_json_decode_error(&encoded, &error);
23298                                return Err(common::Error::JsonDecodeError(
23299                                    encoded.to_string(),
23300                                    error,
23301                                ));
23302                            }
23303                        }
23304                    };
23305
23306                    dlg.finished(true);
23307                    return Ok(response);
23308                }
23309            }
23310        }
23311    }
23312
23313    /// User's email address. The special value "me" can be used to indicate the authenticated user.
23314    ///
23315    /// Sets the *user id* path property to the given value.
23316    ///
23317    /// Even though the property as already been set when instantiating this call,
23318    /// we provide this method for API completeness.
23319    pub fn user_id(mut self, new_value: &str) -> UserSettingGetAutoForwardingCall<'a, C> {
23320        self._user_id = new_value.to_string();
23321        self
23322    }
23323    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
23324    /// while executing the actual API request.
23325    ///
23326    /// ````text
23327    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
23328    /// ````
23329    ///
23330    /// Sets the *delegate* property to the given value.
23331    pub fn delegate(
23332        mut self,
23333        new_value: &'a mut dyn common::Delegate,
23334    ) -> UserSettingGetAutoForwardingCall<'a, C> {
23335        self._delegate = Some(new_value);
23336        self
23337    }
23338
23339    /// Set any additional parameter of the query string used in the request.
23340    /// It should be used to set parameters which are not yet available through their own
23341    /// setters.
23342    ///
23343    /// Please note that this method must not be used to set any of the known parameters
23344    /// which have their own setter method. If done anyway, the request will fail.
23345    ///
23346    /// # Additional Parameters
23347    ///
23348    /// * *$.xgafv* (query-string) - V1 error format.
23349    /// * *access_token* (query-string) - OAuth access token.
23350    /// * *alt* (query-string) - Data format for response.
23351    /// * *callback* (query-string) - JSONP
23352    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
23353    /// * *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.
23354    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
23355    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
23356    /// * *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.
23357    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
23358    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
23359    pub fn param<T>(mut self, name: T, value: T) -> UserSettingGetAutoForwardingCall<'a, C>
23360    where
23361        T: AsRef<str>,
23362    {
23363        self._additional_params
23364            .insert(name.as_ref().to_string(), value.as_ref().to_string());
23365        self
23366    }
23367
23368    /// Identifies the authorization scope for the method you are building.
23369    ///
23370    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
23371    /// [`Scope::Readonly`].
23372    ///
23373    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
23374    /// tokens for more than one scope.
23375    ///
23376    /// Usually there is more than one suitable scope to authorize an operation, some of which may
23377    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
23378    /// sufficient, a read-write scope will do as well.
23379    pub fn add_scope<St>(mut self, scope: St) -> UserSettingGetAutoForwardingCall<'a, C>
23380    where
23381        St: AsRef<str>,
23382    {
23383        self._scopes.insert(String::from(scope.as_ref()));
23384        self
23385    }
23386    /// Identifies the authorization scope(s) for the method you are building.
23387    ///
23388    /// See [`Self::add_scope()`] for details.
23389    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingGetAutoForwardingCall<'a, C>
23390    where
23391        I: IntoIterator<Item = St>,
23392        St: AsRef<str>,
23393    {
23394        self._scopes
23395            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
23396        self
23397    }
23398
23399    /// Removes all scopes, and no default scope will be used either.
23400    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
23401    /// for details).
23402    pub fn clear_scopes(mut self) -> UserSettingGetAutoForwardingCall<'a, C> {
23403        self._scopes.clear();
23404        self
23405    }
23406}
23407
23408/// Gets IMAP settings.
23409///
23410/// A builder for the *settings.getImap* method supported by a *user* resource.
23411/// It is not used directly, but through a [`UserMethods`] instance.
23412///
23413/// # Example
23414///
23415/// Instantiate a resource method builder
23416///
23417/// ```test_harness,no_run
23418/// # extern crate hyper;
23419/// # extern crate hyper_rustls;
23420/// # extern crate google_gmail1 as gmail1;
23421/// # async fn dox() {
23422/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
23423///
23424/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
23425/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
23426/// #     secret,
23427/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
23428/// # ).build().await.unwrap();
23429///
23430/// # let client = hyper_util::client::legacy::Client::builder(
23431/// #     hyper_util::rt::TokioExecutor::new()
23432/// # )
23433/// # .build(
23434/// #     hyper_rustls::HttpsConnectorBuilder::new()
23435/// #         .with_native_roots()
23436/// #         .unwrap()
23437/// #         .https_or_http()
23438/// #         .enable_http1()
23439/// #         .build()
23440/// # );
23441/// # let mut hub = Gmail::new(client, auth);
23442/// // You can configure optional parameters by calling the respective setters at will, and
23443/// // execute the final call using `doit()`.
23444/// // Values shown here are possibly random and not representative !
23445/// let result = hub.users().settings_get_imap("userId")
23446///              .doit().await;
23447/// # }
23448/// ```
23449pub struct UserSettingGetImapCall<'a, C>
23450where
23451    C: 'a,
23452{
23453    hub: &'a Gmail<C>,
23454    _user_id: String,
23455    _delegate: Option<&'a mut dyn common::Delegate>,
23456    _additional_params: HashMap<String, String>,
23457    _scopes: BTreeSet<String>,
23458}
23459
23460impl<'a, C> common::CallBuilder for UserSettingGetImapCall<'a, C> {}
23461
23462impl<'a, C> UserSettingGetImapCall<'a, C>
23463where
23464    C: common::Connector,
23465{
23466    /// Perform the operation you have build so far.
23467    pub async fn doit(mut self) -> common::Result<(common::Response, ImapSettings)> {
23468        use std::borrow::Cow;
23469        use std::io::{Read, Seek};
23470
23471        use common::{url::Params, ToParts};
23472        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
23473
23474        let mut dd = common::DefaultDelegate;
23475        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
23476        dlg.begin(common::MethodInfo {
23477            id: "gmail.users.settings.getImap",
23478            http_method: hyper::Method::GET,
23479        });
23480
23481        for &field in ["alt", "userId"].iter() {
23482            if self._additional_params.contains_key(field) {
23483                dlg.finished(false);
23484                return Err(common::Error::FieldClash(field));
23485            }
23486        }
23487
23488        let mut params = Params::with_capacity(3 + self._additional_params.len());
23489        params.push("userId", self._user_id);
23490
23491        params.extend(self._additional_params.iter());
23492
23493        params.push("alt", "json");
23494        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/imap";
23495        if self._scopes.is_empty() {
23496            self._scopes.insert(Scope::Readonly.as_ref().to_string());
23497        }
23498
23499        #[allow(clippy::single_element_loop)]
23500        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
23501            url = params.uri_replacement(url, param_name, find_this, false);
23502        }
23503        {
23504            let to_remove = ["userId"];
23505            params.remove_params(&to_remove);
23506        }
23507
23508        let url = params.parse_with_url(&url);
23509
23510        loop {
23511            let token = match self
23512                .hub
23513                .auth
23514                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
23515                .await
23516            {
23517                Ok(token) => token,
23518                Err(e) => match dlg.token(e) {
23519                    Ok(token) => token,
23520                    Err(e) => {
23521                        dlg.finished(false);
23522                        return Err(common::Error::MissingToken(e));
23523                    }
23524                },
23525            };
23526            let mut req_result = {
23527                let client = &self.hub.client;
23528                dlg.pre_request();
23529                let mut req_builder = hyper::Request::builder()
23530                    .method(hyper::Method::GET)
23531                    .uri(url.as_str())
23532                    .header(USER_AGENT, self.hub._user_agent.clone());
23533
23534                if let Some(token) = token.as_ref() {
23535                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
23536                }
23537
23538                let request = req_builder
23539                    .header(CONTENT_LENGTH, 0_u64)
23540                    .body(common::to_body::<String>(None));
23541
23542                client.request(request.unwrap()).await
23543            };
23544
23545            match req_result {
23546                Err(err) => {
23547                    if let common::Retry::After(d) = dlg.http_error(&err) {
23548                        sleep(d).await;
23549                        continue;
23550                    }
23551                    dlg.finished(false);
23552                    return Err(common::Error::HttpError(err));
23553                }
23554                Ok(res) => {
23555                    let (mut parts, body) = res.into_parts();
23556                    let mut body = common::Body::new(body);
23557                    if !parts.status.is_success() {
23558                        let bytes = common::to_bytes(body).await.unwrap_or_default();
23559                        let error = serde_json::from_str(&common::to_string(&bytes));
23560                        let response = common::to_response(parts, bytes.into());
23561
23562                        if let common::Retry::After(d) =
23563                            dlg.http_failure(&response, error.as_ref().ok())
23564                        {
23565                            sleep(d).await;
23566                            continue;
23567                        }
23568
23569                        dlg.finished(false);
23570
23571                        return Err(match error {
23572                            Ok(value) => common::Error::BadRequest(value),
23573                            _ => common::Error::Failure(response),
23574                        });
23575                    }
23576                    let response = {
23577                        let bytes = common::to_bytes(body).await.unwrap_or_default();
23578                        let encoded = common::to_string(&bytes);
23579                        match serde_json::from_str(&encoded) {
23580                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
23581                            Err(error) => {
23582                                dlg.response_json_decode_error(&encoded, &error);
23583                                return Err(common::Error::JsonDecodeError(
23584                                    encoded.to_string(),
23585                                    error,
23586                                ));
23587                            }
23588                        }
23589                    };
23590
23591                    dlg.finished(true);
23592                    return Ok(response);
23593                }
23594            }
23595        }
23596    }
23597
23598    /// User's email address. The special value "me" can be used to indicate the authenticated user.
23599    ///
23600    /// Sets the *user id* path property to the given value.
23601    ///
23602    /// Even though the property as already been set when instantiating this call,
23603    /// we provide this method for API completeness.
23604    pub fn user_id(mut self, new_value: &str) -> UserSettingGetImapCall<'a, C> {
23605        self._user_id = new_value.to_string();
23606        self
23607    }
23608    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
23609    /// while executing the actual API request.
23610    ///
23611    /// ````text
23612    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
23613    /// ````
23614    ///
23615    /// Sets the *delegate* property to the given value.
23616    pub fn delegate(
23617        mut self,
23618        new_value: &'a mut dyn common::Delegate,
23619    ) -> UserSettingGetImapCall<'a, C> {
23620        self._delegate = Some(new_value);
23621        self
23622    }
23623
23624    /// Set any additional parameter of the query string used in the request.
23625    /// It should be used to set parameters which are not yet available through their own
23626    /// setters.
23627    ///
23628    /// Please note that this method must not be used to set any of the known parameters
23629    /// which have their own setter method. If done anyway, the request will fail.
23630    ///
23631    /// # Additional Parameters
23632    ///
23633    /// * *$.xgafv* (query-string) - V1 error format.
23634    /// * *access_token* (query-string) - OAuth access token.
23635    /// * *alt* (query-string) - Data format for response.
23636    /// * *callback* (query-string) - JSONP
23637    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
23638    /// * *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.
23639    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
23640    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
23641    /// * *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.
23642    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
23643    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
23644    pub fn param<T>(mut self, name: T, value: T) -> UserSettingGetImapCall<'a, C>
23645    where
23646        T: AsRef<str>,
23647    {
23648        self._additional_params
23649            .insert(name.as_ref().to_string(), value.as_ref().to_string());
23650        self
23651    }
23652
23653    /// Identifies the authorization scope for the method you are building.
23654    ///
23655    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
23656    /// [`Scope::Readonly`].
23657    ///
23658    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
23659    /// tokens for more than one scope.
23660    ///
23661    /// Usually there is more than one suitable scope to authorize an operation, some of which may
23662    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
23663    /// sufficient, a read-write scope will do as well.
23664    pub fn add_scope<St>(mut self, scope: St) -> UserSettingGetImapCall<'a, C>
23665    where
23666        St: AsRef<str>,
23667    {
23668        self._scopes.insert(String::from(scope.as_ref()));
23669        self
23670    }
23671    /// Identifies the authorization scope(s) for the method you are building.
23672    ///
23673    /// See [`Self::add_scope()`] for details.
23674    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingGetImapCall<'a, C>
23675    where
23676        I: IntoIterator<Item = St>,
23677        St: AsRef<str>,
23678    {
23679        self._scopes
23680            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
23681        self
23682    }
23683
23684    /// Removes all scopes, and no default scope will be used either.
23685    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
23686    /// for details).
23687    pub fn clear_scopes(mut self) -> UserSettingGetImapCall<'a, C> {
23688        self._scopes.clear();
23689        self
23690    }
23691}
23692
23693/// Gets language settings.
23694///
23695/// A builder for the *settings.getLanguage* method supported by a *user* resource.
23696/// It is not used directly, but through a [`UserMethods`] instance.
23697///
23698/// # Example
23699///
23700/// Instantiate a resource method builder
23701///
23702/// ```test_harness,no_run
23703/// # extern crate hyper;
23704/// # extern crate hyper_rustls;
23705/// # extern crate google_gmail1 as gmail1;
23706/// # async fn dox() {
23707/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
23708///
23709/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
23710/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
23711/// #     secret,
23712/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
23713/// # ).build().await.unwrap();
23714///
23715/// # let client = hyper_util::client::legacy::Client::builder(
23716/// #     hyper_util::rt::TokioExecutor::new()
23717/// # )
23718/// # .build(
23719/// #     hyper_rustls::HttpsConnectorBuilder::new()
23720/// #         .with_native_roots()
23721/// #         .unwrap()
23722/// #         .https_or_http()
23723/// #         .enable_http1()
23724/// #         .build()
23725/// # );
23726/// # let mut hub = Gmail::new(client, auth);
23727/// // You can configure optional parameters by calling the respective setters at will, and
23728/// // execute the final call using `doit()`.
23729/// // Values shown here are possibly random and not representative !
23730/// let result = hub.users().settings_get_language("userId")
23731///              .doit().await;
23732/// # }
23733/// ```
23734pub struct UserSettingGetLanguageCall<'a, C>
23735where
23736    C: 'a,
23737{
23738    hub: &'a Gmail<C>,
23739    _user_id: String,
23740    _delegate: Option<&'a mut dyn common::Delegate>,
23741    _additional_params: HashMap<String, String>,
23742    _scopes: BTreeSet<String>,
23743}
23744
23745impl<'a, C> common::CallBuilder for UserSettingGetLanguageCall<'a, C> {}
23746
23747impl<'a, C> UserSettingGetLanguageCall<'a, C>
23748where
23749    C: common::Connector,
23750{
23751    /// Perform the operation you have build so far.
23752    pub async fn doit(mut self) -> common::Result<(common::Response, LanguageSettings)> {
23753        use std::borrow::Cow;
23754        use std::io::{Read, Seek};
23755
23756        use common::{url::Params, ToParts};
23757        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
23758
23759        let mut dd = common::DefaultDelegate;
23760        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
23761        dlg.begin(common::MethodInfo {
23762            id: "gmail.users.settings.getLanguage",
23763            http_method: hyper::Method::GET,
23764        });
23765
23766        for &field in ["alt", "userId"].iter() {
23767            if self._additional_params.contains_key(field) {
23768                dlg.finished(false);
23769                return Err(common::Error::FieldClash(field));
23770            }
23771        }
23772
23773        let mut params = Params::with_capacity(3 + self._additional_params.len());
23774        params.push("userId", self._user_id);
23775
23776        params.extend(self._additional_params.iter());
23777
23778        params.push("alt", "json");
23779        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/language";
23780        if self._scopes.is_empty() {
23781            self._scopes.insert(Scope::Readonly.as_ref().to_string());
23782        }
23783
23784        #[allow(clippy::single_element_loop)]
23785        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
23786            url = params.uri_replacement(url, param_name, find_this, false);
23787        }
23788        {
23789            let to_remove = ["userId"];
23790            params.remove_params(&to_remove);
23791        }
23792
23793        let url = params.parse_with_url(&url);
23794
23795        loop {
23796            let token = match self
23797                .hub
23798                .auth
23799                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
23800                .await
23801            {
23802                Ok(token) => token,
23803                Err(e) => match dlg.token(e) {
23804                    Ok(token) => token,
23805                    Err(e) => {
23806                        dlg.finished(false);
23807                        return Err(common::Error::MissingToken(e));
23808                    }
23809                },
23810            };
23811            let mut req_result = {
23812                let client = &self.hub.client;
23813                dlg.pre_request();
23814                let mut req_builder = hyper::Request::builder()
23815                    .method(hyper::Method::GET)
23816                    .uri(url.as_str())
23817                    .header(USER_AGENT, self.hub._user_agent.clone());
23818
23819                if let Some(token) = token.as_ref() {
23820                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
23821                }
23822
23823                let request = req_builder
23824                    .header(CONTENT_LENGTH, 0_u64)
23825                    .body(common::to_body::<String>(None));
23826
23827                client.request(request.unwrap()).await
23828            };
23829
23830            match req_result {
23831                Err(err) => {
23832                    if let common::Retry::After(d) = dlg.http_error(&err) {
23833                        sleep(d).await;
23834                        continue;
23835                    }
23836                    dlg.finished(false);
23837                    return Err(common::Error::HttpError(err));
23838                }
23839                Ok(res) => {
23840                    let (mut parts, body) = res.into_parts();
23841                    let mut body = common::Body::new(body);
23842                    if !parts.status.is_success() {
23843                        let bytes = common::to_bytes(body).await.unwrap_or_default();
23844                        let error = serde_json::from_str(&common::to_string(&bytes));
23845                        let response = common::to_response(parts, bytes.into());
23846
23847                        if let common::Retry::After(d) =
23848                            dlg.http_failure(&response, error.as_ref().ok())
23849                        {
23850                            sleep(d).await;
23851                            continue;
23852                        }
23853
23854                        dlg.finished(false);
23855
23856                        return Err(match error {
23857                            Ok(value) => common::Error::BadRequest(value),
23858                            _ => common::Error::Failure(response),
23859                        });
23860                    }
23861                    let response = {
23862                        let bytes = common::to_bytes(body).await.unwrap_or_default();
23863                        let encoded = common::to_string(&bytes);
23864                        match serde_json::from_str(&encoded) {
23865                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
23866                            Err(error) => {
23867                                dlg.response_json_decode_error(&encoded, &error);
23868                                return Err(common::Error::JsonDecodeError(
23869                                    encoded.to_string(),
23870                                    error,
23871                                ));
23872                            }
23873                        }
23874                    };
23875
23876                    dlg.finished(true);
23877                    return Ok(response);
23878                }
23879            }
23880        }
23881    }
23882
23883    /// User's email address. The special value "me" can be used to indicate the authenticated user.
23884    ///
23885    /// Sets the *user id* path property to the given value.
23886    ///
23887    /// Even though the property as already been set when instantiating this call,
23888    /// we provide this method for API completeness.
23889    pub fn user_id(mut self, new_value: &str) -> UserSettingGetLanguageCall<'a, C> {
23890        self._user_id = new_value.to_string();
23891        self
23892    }
23893    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
23894    /// while executing the actual API request.
23895    ///
23896    /// ````text
23897    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
23898    /// ````
23899    ///
23900    /// Sets the *delegate* property to the given value.
23901    pub fn delegate(
23902        mut self,
23903        new_value: &'a mut dyn common::Delegate,
23904    ) -> UserSettingGetLanguageCall<'a, C> {
23905        self._delegate = Some(new_value);
23906        self
23907    }
23908
23909    /// Set any additional parameter of the query string used in the request.
23910    /// It should be used to set parameters which are not yet available through their own
23911    /// setters.
23912    ///
23913    /// Please note that this method must not be used to set any of the known parameters
23914    /// which have their own setter method. If done anyway, the request will fail.
23915    ///
23916    /// # Additional Parameters
23917    ///
23918    /// * *$.xgafv* (query-string) - V1 error format.
23919    /// * *access_token* (query-string) - OAuth access token.
23920    /// * *alt* (query-string) - Data format for response.
23921    /// * *callback* (query-string) - JSONP
23922    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
23923    /// * *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.
23924    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
23925    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
23926    /// * *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.
23927    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
23928    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
23929    pub fn param<T>(mut self, name: T, value: T) -> UserSettingGetLanguageCall<'a, C>
23930    where
23931        T: AsRef<str>,
23932    {
23933        self._additional_params
23934            .insert(name.as_ref().to_string(), value.as_ref().to_string());
23935        self
23936    }
23937
23938    /// Identifies the authorization scope for the method you are building.
23939    ///
23940    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
23941    /// [`Scope::Readonly`].
23942    ///
23943    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
23944    /// tokens for more than one scope.
23945    ///
23946    /// Usually there is more than one suitable scope to authorize an operation, some of which may
23947    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
23948    /// sufficient, a read-write scope will do as well.
23949    pub fn add_scope<St>(mut self, scope: St) -> UserSettingGetLanguageCall<'a, C>
23950    where
23951        St: AsRef<str>,
23952    {
23953        self._scopes.insert(String::from(scope.as_ref()));
23954        self
23955    }
23956    /// Identifies the authorization scope(s) for the method you are building.
23957    ///
23958    /// See [`Self::add_scope()`] for details.
23959    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingGetLanguageCall<'a, C>
23960    where
23961        I: IntoIterator<Item = St>,
23962        St: AsRef<str>,
23963    {
23964        self._scopes
23965            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
23966        self
23967    }
23968
23969    /// Removes all scopes, and no default scope will be used either.
23970    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
23971    /// for details).
23972    pub fn clear_scopes(mut self) -> UserSettingGetLanguageCall<'a, C> {
23973        self._scopes.clear();
23974        self
23975    }
23976}
23977
23978/// Gets POP settings.
23979///
23980/// A builder for the *settings.getPop* method supported by a *user* resource.
23981/// It is not used directly, but through a [`UserMethods`] instance.
23982///
23983/// # Example
23984///
23985/// Instantiate a resource method builder
23986///
23987/// ```test_harness,no_run
23988/// # extern crate hyper;
23989/// # extern crate hyper_rustls;
23990/// # extern crate google_gmail1 as gmail1;
23991/// # async fn dox() {
23992/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
23993///
23994/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
23995/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
23996/// #     secret,
23997/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
23998/// # ).build().await.unwrap();
23999///
24000/// # let client = hyper_util::client::legacy::Client::builder(
24001/// #     hyper_util::rt::TokioExecutor::new()
24002/// # )
24003/// # .build(
24004/// #     hyper_rustls::HttpsConnectorBuilder::new()
24005/// #         .with_native_roots()
24006/// #         .unwrap()
24007/// #         .https_or_http()
24008/// #         .enable_http1()
24009/// #         .build()
24010/// # );
24011/// # let mut hub = Gmail::new(client, auth);
24012/// // You can configure optional parameters by calling the respective setters at will, and
24013/// // execute the final call using `doit()`.
24014/// // Values shown here are possibly random and not representative !
24015/// let result = hub.users().settings_get_pop("userId")
24016///              .doit().await;
24017/// # }
24018/// ```
24019pub struct UserSettingGetPopCall<'a, C>
24020where
24021    C: 'a,
24022{
24023    hub: &'a Gmail<C>,
24024    _user_id: String,
24025    _delegate: Option<&'a mut dyn common::Delegate>,
24026    _additional_params: HashMap<String, String>,
24027    _scopes: BTreeSet<String>,
24028}
24029
24030impl<'a, C> common::CallBuilder for UserSettingGetPopCall<'a, C> {}
24031
24032impl<'a, C> UserSettingGetPopCall<'a, C>
24033where
24034    C: common::Connector,
24035{
24036    /// Perform the operation you have build so far.
24037    pub async fn doit(mut self) -> common::Result<(common::Response, PopSettings)> {
24038        use std::borrow::Cow;
24039        use std::io::{Read, Seek};
24040
24041        use common::{url::Params, ToParts};
24042        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
24043
24044        let mut dd = common::DefaultDelegate;
24045        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
24046        dlg.begin(common::MethodInfo {
24047            id: "gmail.users.settings.getPop",
24048            http_method: hyper::Method::GET,
24049        });
24050
24051        for &field in ["alt", "userId"].iter() {
24052            if self._additional_params.contains_key(field) {
24053                dlg.finished(false);
24054                return Err(common::Error::FieldClash(field));
24055            }
24056        }
24057
24058        let mut params = Params::with_capacity(3 + self._additional_params.len());
24059        params.push("userId", self._user_id);
24060
24061        params.extend(self._additional_params.iter());
24062
24063        params.push("alt", "json");
24064        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/pop";
24065        if self._scopes.is_empty() {
24066            self._scopes.insert(Scope::Readonly.as_ref().to_string());
24067        }
24068
24069        #[allow(clippy::single_element_loop)]
24070        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
24071            url = params.uri_replacement(url, param_name, find_this, false);
24072        }
24073        {
24074            let to_remove = ["userId"];
24075            params.remove_params(&to_remove);
24076        }
24077
24078        let url = params.parse_with_url(&url);
24079
24080        loop {
24081            let token = match self
24082                .hub
24083                .auth
24084                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
24085                .await
24086            {
24087                Ok(token) => token,
24088                Err(e) => match dlg.token(e) {
24089                    Ok(token) => token,
24090                    Err(e) => {
24091                        dlg.finished(false);
24092                        return Err(common::Error::MissingToken(e));
24093                    }
24094                },
24095            };
24096            let mut req_result = {
24097                let client = &self.hub.client;
24098                dlg.pre_request();
24099                let mut req_builder = hyper::Request::builder()
24100                    .method(hyper::Method::GET)
24101                    .uri(url.as_str())
24102                    .header(USER_AGENT, self.hub._user_agent.clone());
24103
24104                if let Some(token) = token.as_ref() {
24105                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
24106                }
24107
24108                let request = req_builder
24109                    .header(CONTENT_LENGTH, 0_u64)
24110                    .body(common::to_body::<String>(None));
24111
24112                client.request(request.unwrap()).await
24113            };
24114
24115            match req_result {
24116                Err(err) => {
24117                    if let common::Retry::After(d) = dlg.http_error(&err) {
24118                        sleep(d).await;
24119                        continue;
24120                    }
24121                    dlg.finished(false);
24122                    return Err(common::Error::HttpError(err));
24123                }
24124                Ok(res) => {
24125                    let (mut parts, body) = res.into_parts();
24126                    let mut body = common::Body::new(body);
24127                    if !parts.status.is_success() {
24128                        let bytes = common::to_bytes(body).await.unwrap_or_default();
24129                        let error = serde_json::from_str(&common::to_string(&bytes));
24130                        let response = common::to_response(parts, bytes.into());
24131
24132                        if let common::Retry::After(d) =
24133                            dlg.http_failure(&response, error.as_ref().ok())
24134                        {
24135                            sleep(d).await;
24136                            continue;
24137                        }
24138
24139                        dlg.finished(false);
24140
24141                        return Err(match error {
24142                            Ok(value) => common::Error::BadRequest(value),
24143                            _ => common::Error::Failure(response),
24144                        });
24145                    }
24146                    let response = {
24147                        let bytes = common::to_bytes(body).await.unwrap_or_default();
24148                        let encoded = common::to_string(&bytes);
24149                        match serde_json::from_str(&encoded) {
24150                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
24151                            Err(error) => {
24152                                dlg.response_json_decode_error(&encoded, &error);
24153                                return Err(common::Error::JsonDecodeError(
24154                                    encoded.to_string(),
24155                                    error,
24156                                ));
24157                            }
24158                        }
24159                    };
24160
24161                    dlg.finished(true);
24162                    return Ok(response);
24163                }
24164            }
24165        }
24166    }
24167
24168    /// User's email address. The special value "me" can be used to indicate the authenticated user.
24169    ///
24170    /// Sets the *user id* path property to the given value.
24171    ///
24172    /// Even though the property as already been set when instantiating this call,
24173    /// we provide this method for API completeness.
24174    pub fn user_id(mut self, new_value: &str) -> UserSettingGetPopCall<'a, C> {
24175        self._user_id = new_value.to_string();
24176        self
24177    }
24178    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
24179    /// while executing the actual API request.
24180    ///
24181    /// ````text
24182    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
24183    /// ````
24184    ///
24185    /// Sets the *delegate* property to the given value.
24186    pub fn delegate(
24187        mut self,
24188        new_value: &'a mut dyn common::Delegate,
24189    ) -> UserSettingGetPopCall<'a, C> {
24190        self._delegate = Some(new_value);
24191        self
24192    }
24193
24194    /// Set any additional parameter of the query string used in the request.
24195    /// It should be used to set parameters which are not yet available through their own
24196    /// setters.
24197    ///
24198    /// Please note that this method must not be used to set any of the known parameters
24199    /// which have their own setter method. If done anyway, the request will fail.
24200    ///
24201    /// # Additional Parameters
24202    ///
24203    /// * *$.xgafv* (query-string) - V1 error format.
24204    /// * *access_token* (query-string) - OAuth access token.
24205    /// * *alt* (query-string) - Data format for response.
24206    /// * *callback* (query-string) - JSONP
24207    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
24208    /// * *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.
24209    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
24210    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
24211    /// * *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.
24212    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
24213    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
24214    pub fn param<T>(mut self, name: T, value: T) -> UserSettingGetPopCall<'a, C>
24215    where
24216        T: AsRef<str>,
24217    {
24218        self._additional_params
24219            .insert(name.as_ref().to_string(), value.as_ref().to_string());
24220        self
24221    }
24222
24223    /// Identifies the authorization scope for the method you are building.
24224    ///
24225    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
24226    /// [`Scope::Readonly`].
24227    ///
24228    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
24229    /// tokens for more than one scope.
24230    ///
24231    /// Usually there is more than one suitable scope to authorize an operation, some of which may
24232    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
24233    /// sufficient, a read-write scope will do as well.
24234    pub fn add_scope<St>(mut self, scope: St) -> UserSettingGetPopCall<'a, C>
24235    where
24236        St: AsRef<str>,
24237    {
24238        self._scopes.insert(String::from(scope.as_ref()));
24239        self
24240    }
24241    /// Identifies the authorization scope(s) for the method you are building.
24242    ///
24243    /// See [`Self::add_scope()`] for details.
24244    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingGetPopCall<'a, C>
24245    where
24246        I: IntoIterator<Item = St>,
24247        St: AsRef<str>,
24248    {
24249        self._scopes
24250            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
24251        self
24252    }
24253
24254    /// Removes all scopes, and no default scope will be used either.
24255    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
24256    /// for details).
24257    pub fn clear_scopes(mut self) -> UserSettingGetPopCall<'a, C> {
24258        self._scopes.clear();
24259        self
24260    }
24261}
24262
24263/// Gets vacation responder settings.
24264///
24265/// A builder for the *settings.getVacation* method supported by a *user* resource.
24266/// It is not used directly, but through a [`UserMethods`] instance.
24267///
24268/// # Example
24269///
24270/// Instantiate a resource method builder
24271///
24272/// ```test_harness,no_run
24273/// # extern crate hyper;
24274/// # extern crate hyper_rustls;
24275/// # extern crate google_gmail1 as gmail1;
24276/// # async fn dox() {
24277/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
24278///
24279/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
24280/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
24281/// #     secret,
24282/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
24283/// # ).build().await.unwrap();
24284///
24285/// # let client = hyper_util::client::legacy::Client::builder(
24286/// #     hyper_util::rt::TokioExecutor::new()
24287/// # )
24288/// # .build(
24289/// #     hyper_rustls::HttpsConnectorBuilder::new()
24290/// #         .with_native_roots()
24291/// #         .unwrap()
24292/// #         .https_or_http()
24293/// #         .enable_http1()
24294/// #         .build()
24295/// # );
24296/// # let mut hub = Gmail::new(client, auth);
24297/// // You can configure optional parameters by calling the respective setters at will, and
24298/// // execute the final call using `doit()`.
24299/// // Values shown here are possibly random and not representative !
24300/// let result = hub.users().settings_get_vacation("userId")
24301///              .doit().await;
24302/// # }
24303/// ```
24304pub struct UserSettingGetVacationCall<'a, C>
24305where
24306    C: 'a,
24307{
24308    hub: &'a Gmail<C>,
24309    _user_id: String,
24310    _delegate: Option<&'a mut dyn common::Delegate>,
24311    _additional_params: HashMap<String, String>,
24312    _scopes: BTreeSet<String>,
24313}
24314
24315impl<'a, C> common::CallBuilder for UserSettingGetVacationCall<'a, C> {}
24316
24317impl<'a, C> UserSettingGetVacationCall<'a, C>
24318where
24319    C: common::Connector,
24320{
24321    /// Perform the operation you have build so far.
24322    pub async fn doit(mut self) -> common::Result<(common::Response, VacationSettings)> {
24323        use std::borrow::Cow;
24324        use std::io::{Read, Seek};
24325
24326        use common::{url::Params, ToParts};
24327        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
24328
24329        let mut dd = common::DefaultDelegate;
24330        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
24331        dlg.begin(common::MethodInfo {
24332            id: "gmail.users.settings.getVacation",
24333            http_method: hyper::Method::GET,
24334        });
24335
24336        for &field in ["alt", "userId"].iter() {
24337            if self._additional_params.contains_key(field) {
24338                dlg.finished(false);
24339                return Err(common::Error::FieldClash(field));
24340            }
24341        }
24342
24343        let mut params = Params::with_capacity(3 + self._additional_params.len());
24344        params.push("userId", self._user_id);
24345
24346        params.extend(self._additional_params.iter());
24347
24348        params.push("alt", "json");
24349        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/vacation";
24350        if self._scopes.is_empty() {
24351            self._scopes.insert(Scope::Readonly.as_ref().to_string());
24352        }
24353
24354        #[allow(clippy::single_element_loop)]
24355        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
24356            url = params.uri_replacement(url, param_name, find_this, false);
24357        }
24358        {
24359            let to_remove = ["userId"];
24360            params.remove_params(&to_remove);
24361        }
24362
24363        let url = params.parse_with_url(&url);
24364
24365        loop {
24366            let token = match self
24367                .hub
24368                .auth
24369                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
24370                .await
24371            {
24372                Ok(token) => token,
24373                Err(e) => match dlg.token(e) {
24374                    Ok(token) => token,
24375                    Err(e) => {
24376                        dlg.finished(false);
24377                        return Err(common::Error::MissingToken(e));
24378                    }
24379                },
24380            };
24381            let mut req_result = {
24382                let client = &self.hub.client;
24383                dlg.pre_request();
24384                let mut req_builder = hyper::Request::builder()
24385                    .method(hyper::Method::GET)
24386                    .uri(url.as_str())
24387                    .header(USER_AGENT, self.hub._user_agent.clone());
24388
24389                if let Some(token) = token.as_ref() {
24390                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
24391                }
24392
24393                let request = req_builder
24394                    .header(CONTENT_LENGTH, 0_u64)
24395                    .body(common::to_body::<String>(None));
24396
24397                client.request(request.unwrap()).await
24398            };
24399
24400            match req_result {
24401                Err(err) => {
24402                    if let common::Retry::After(d) = dlg.http_error(&err) {
24403                        sleep(d).await;
24404                        continue;
24405                    }
24406                    dlg.finished(false);
24407                    return Err(common::Error::HttpError(err));
24408                }
24409                Ok(res) => {
24410                    let (mut parts, body) = res.into_parts();
24411                    let mut body = common::Body::new(body);
24412                    if !parts.status.is_success() {
24413                        let bytes = common::to_bytes(body).await.unwrap_or_default();
24414                        let error = serde_json::from_str(&common::to_string(&bytes));
24415                        let response = common::to_response(parts, bytes.into());
24416
24417                        if let common::Retry::After(d) =
24418                            dlg.http_failure(&response, error.as_ref().ok())
24419                        {
24420                            sleep(d).await;
24421                            continue;
24422                        }
24423
24424                        dlg.finished(false);
24425
24426                        return Err(match error {
24427                            Ok(value) => common::Error::BadRequest(value),
24428                            _ => common::Error::Failure(response),
24429                        });
24430                    }
24431                    let response = {
24432                        let bytes = common::to_bytes(body).await.unwrap_or_default();
24433                        let encoded = common::to_string(&bytes);
24434                        match serde_json::from_str(&encoded) {
24435                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
24436                            Err(error) => {
24437                                dlg.response_json_decode_error(&encoded, &error);
24438                                return Err(common::Error::JsonDecodeError(
24439                                    encoded.to_string(),
24440                                    error,
24441                                ));
24442                            }
24443                        }
24444                    };
24445
24446                    dlg.finished(true);
24447                    return Ok(response);
24448                }
24449            }
24450        }
24451    }
24452
24453    /// User's email address. The special value "me" can be used to indicate the authenticated user.
24454    ///
24455    /// Sets the *user id* path property to the given value.
24456    ///
24457    /// Even though the property as already been set when instantiating this call,
24458    /// we provide this method for API completeness.
24459    pub fn user_id(mut self, new_value: &str) -> UserSettingGetVacationCall<'a, C> {
24460        self._user_id = new_value.to_string();
24461        self
24462    }
24463    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
24464    /// while executing the actual API request.
24465    ///
24466    /// ````text
24467    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
24468    /// ````
24469    ///
24470    /// Sets the *delegate* property to the given value.
24471    pub fn delegate(
24472        mut self,
24473        new_value: &'a mut dyn common::Delegate,
24474    ) -> UserSettingGetVacationCall<'a, C> {
24475        self._delegate = Some(new_value);
24476        self
24477    }
24478
24479    /// Set any additional parameter of the query string used in the request.
24480    /// It should be used to set parameters which are not yet available through their own
24481    /// setters.
24482    ///
24483    /// Please note that this method must not be used to set any of the known parameters
24484    /// which have their own setter method. If done anyway, the request will fail.
24485    ///
24486    /// # Additional Parameters
24487    ///
24488    /// * *$.xgafv* (query-string) - V1 error format.
24489    /// * *access_token* (query-string) - OAuth access token.
24490    /// * *alt* (query-string) - Data format for response.
24491    /// * *callback* (query-string) - JSONP
24492    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
24493    /// * *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.
24494    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
24495    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
24496    /// * *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.
24497    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
24498    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
24499    pub fn param<T>(mut self, name: T, value: T) -> UserSettingGetVacationCall<'a, C>
24500    where
24501        T: AsRef<str>,
24502    {
24503        self._additional_params
24504            .insert(name.as_ref().to_string(), value.as_ref().to_string());
24505        self
24506    }
24507
24508    /// Identifies the authorization scope for the method you are building.
24509    ///
24510    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
24511    /// [`Scope::Readonly`].
24512    ///
24513    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
24514    /// tokens for more than one scope.
24515    ///
24516    /// Usually there is more than one suitable scope to authorize an operation, some of which may
24517    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
24518    /// sufficient, a read-write scope will do as well.
24519    pub fn add_scope<St>(mut self, scope: St) -> UserSettingGetVacationCall<'a, C>
24520    where
24521        St: AsRef<str>,
24522    {
24523        self._scopes.insert(String::from(scope.as_ref()));
24524        self
24525    }
24526    /// Identifies the authorization scope(s) for the method you are building.
24527    ///
24528    /// See [`Self::add_scope()`] for details.
24529    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingGetVacationCall<'a, C>
24530    where
24531        I: IntoIterator<Item = St>,
24532        St: AsRef<str>,
24533    {
24534        self._scopes
24535            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
24536        self
24537    }
24538
24539    /// Removes all scopes, and no default scope will be used either.
24540    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
24541    /// for details).
24542    pub fn clear_scopes(mut self) -> UserSettingGetVacationCall<'a, C> {
24543        self._scopes.clear();
24544        self
24545    }
24546}
24547
24548/// Updates the auto-forwarding setting for the specified account. A verified forwarding address must be specified when auto-forwarding is enabled. This method is only available to service account clients that have been delegated domain-wide authority.
24549///
24550/// A builder for the *settings.updateAutoForwarding* method supported by a *user* resource.
24551/// It is not used directly, but through a [`UserMethods`] instance.
24552///
24553/// # Example
24554///
24555/// Instantiate a resource method builder
24556///
24557/// ```test_harness,no_run
24558/// # extern crate hyper;
24559/// # extern crate hyper_rustls;
24560/// # extern crate google_gmail1 as gmail1;
24561/// use gmail1::api::AutoForwarding;
24562/// # async fn dox() {
24563/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
24564///
24565/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
24566/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
24567/// #     secret,
24568/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
24569/// # ).build().await.unwrap();
24570///
24571/// # let client = hyper_util::client::legacy::Client::builder(
24572/// #     hyper_util::rt::TokioExecutor::new()
24573/// # )
24574/// # .build(
24575/// #     hyper_rustls::HttpsConnectorBuilder::new()
24576/// #         .with_native_roots()
24577/// #         .unwrap()
24578/// #         .https_or_http()
24579/// #         .enable_http1()
24580/// #         .build()
24581/// # );
24582/// # let mut hub = Gmail::new(client, auth);
24583/// // As the method needs a request, you would usually fill it with the desired information
24584/// // into the respective structure. Some of the parts shown here might not be applicable !
24585/// // Values shown here are possibly random and not representative !
24586/// let mut req = AutoForwarding::default();
24587///
24588/// // You can configure optional parameters by calling the respective setters at will, and
24589/// // execute the final call using `doit()`.
24590/// // Values shown here are possibly random and not representative !
24591/// let result = hub.users().settings_update_auto_forwarding(req, "userId")
24592///              .doit().await;
24593/// # }
24594/// ```
24595pub struct UserSettingUpdateAutoForwardingCall<'a, C>
24596where
24597    C: 'a,
24598{
24599    hub: &'a Gmail<C>,
24600    _request: AutoForwarding,
24601    _user_id: String,
24602    _delegate: Option<&'a mut dyn common::Delegate>,
24603    _additional_params: HashMap<String, String>,
24604    _scopes: BTreeSet<String>,
24605}
24606
24607impl<'a, C> common::CallBuilder for UserSettingUpdateAutoForwardingCall<'a, C> {}
24608
24609impl<'a, C> UserSettingUpdateAutoForwardingCall<'a, C>
24610where
24611    C: common::Connector,
24612{
24613    /// Perform the operation you have build so far.
24614    pub async fn doit(mut self) -> common::Result<(common::Response, AutoForwarding)> {
24615        use std::borrow::Cow;
24616        use std::io::{Read, Seek};
24617
24618        use common::{url::Params, ToParts};
24619        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
24620
24621        let mut dd = common::DefaultDelegate;
24622        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
24623        dlg.begin(common::MethodInfo {
24624            id: "gmail.users.settings.updateAutoForwarding",
24625            http_method: hyper::Method::PUT,
24626        });
24627
24628        for &field in ["alt", "userId"].iter() {
24629            if self._additional_params.contains_key(field) {
24630                dlg.finished(false);
24631                return Err(common::Error::FieldClash(field));
24632            }
24633        }
24634
24635        let mut params = Params::with_capacity(4 + self._additional_params.len());
24636        params.push("userId", self._user_id);
24637
24638        params.extend(self._additional_params.iter());
24639
24640        params.push("alt", "json");
24641        let mut url =
24642            self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/autoForwarding";
24643        if self._scopes.is_empty() {
24644            self._scopes
24645                .insert(Scope::SettingSharing.as_ref().to_string());
24646        }
24647
24648        #[allow(clippy::single_element_loop)]
24649        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
24650            url = params.uri_replacement(url, param_name, find_this, false);
24651        }
24652        {
24653            let to_remove = ["userId"];
24654            params.remove_params(&to_remove);
24655        }
24656
24657        let url = params.parse_with_url(&url);
24658
24659        let mut json_mime_type = mime::APPLICATION_JSON;
24660        let mut request_value_reader = {
24661            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
24662            common::remove_json_null_values(&mut value);
24663            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
24664            serde_json::to_writer(&mut dst, &value).unwrap();
24665            dst
24666        };
24667        let request_size = request_value_reader
24668            .seek(std::io::SeekFrom::End(0))
24669            .unwrap();
24670        request_value_reader
24671            .seek(std::io::SeekFrom::Start(0))
24672            .unwrap();
24673
24674        loop {
24675            let token = match self
24676                .hub
24677                .auth
24678                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
24679                .await
24680            {
24681                Ok(token) => token,
24682                Err(e) => match dlg.token(e) {
24683                    Ok(token) => token,
24684                    Err(e) => {
24685                        dlg.finished(false);
24686                        return Err(common::Error::MissingToken(e));
24687                    }
24688                },
24689            };
24690            request_value_reader
24691                .seek(std::io::SeekFrom::Start(0))
24692                .unwrap();
24693            let mut req_result = {
24694                let client = &self.hub.client;
24695                dlg.pre_request();
24696                let mut req_builder = hyper::Request::builder()
24697                    .method(hyper::Method::PUT)
24698                    .uri(url.as_str())
24699                    .header(USER_AGENT, self.hub._user_agent.clone());
24700
24701                if let Some(token) = token.as_ref() {
24702                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
24703                }
24704
24705                let request = req_builder
24706                    .header(CONTENT_TYPE, json_mime_type.to_string())
24707                    .header(CONTENT_LENGTH, request_size as u64)
24708                    .body(common::to_body(
24709                        request_value_reader.get_ref().clone().into(),
24710                    ));
24711
24712                client.request(request.unwrap()).await
24713            };
24714
24715            match req_result {
24716                Err(err) => {
24717                    if let common::Retry::After(d) = dlg.http_error(&err) {
24718                        sleep(d).await;
24719                        continue;
24720                    }
24721                    dlg.finished(false);
24722                    return Err(common::Error::HttpError(err));
24723                }
24724                Ok(res) => {
24725                    let (mut parts, body) = res.into_parts();
24726                    let mut body = common::Body::new(body);
24727                    if !parts.status.is_success() {
24728                        let bytes = common::to_bytes(body).await.unwrap_or_default();
24729                        let error = serde_json::from_str(&common::to_string(&bytes));
24730                        let response = common::to_response(parts, bytes.into());
24731
24732                        if let common::Retry::After(d) =
24733                            dlg.http_failure(&response, error.as_ref().ok())
24734                        {
24735                            sleep(d).await;
24736                            continue;
24737                        }
24738
24739                        dlg.finished(false);
24740
24741                        return Err(match error {
24742                            Ok(value) => common::Error::BadRequest(value),
24743                            _ => common::Error::Failure(response),
24744                        });
24745                    }
24746                    let response = {
24747                        let bytes = common::to_bytes(body).await.unwrap_or_default();
24748                        let encoded = common::to_string(&bytes);
24749                        match serde_json::from_str(&encoded) {
24750                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
24751                            Err(error) => {
24752                                dlg.response_json_decode_error(&encoded, &error);
24753                                return Err(common::Error::JsonDecodeError(
24754                                    encoded.to_string(),
24755                                    error,
24756                                ));
24757                            }
24758                        }
24759                    };
24760
24761                    dlg.finished(true);
24762                    return Ok(response);
24763                }
24764            }
24765        }
24766    }
24767
24768    ///
24769    /// Sets the *request* property to the given value.
24770    ///
24771    /// Even though the property as already been set when instantiating this call,
24772    /// we provide this method for API completeness.
24773    pub fn request(
24774        mut self,
24775        new_value: AutoForwarding,
24776    ) -> UserSettingUpdateAutoForwardingCall<'a, C> {
24777        self._request = new_value;
24778        self
24779    }
24780    /// User's email address. The special value "me" can be used to indicate the authenticated user.
24781    ///
24782    /// Sets the *user id* path property to the given value.
24783    ///
24784    /// Even though the property as already been set when instantiating this call,
24785    /// we provide this method for API completeness.
24786    pub fn user_id(mut self, new_value: &str) -> UserSettingUpdateAutoForwardingCall<'a, C> {
24787        self._user_id = new_value.to_string();
24788        self
24789    }
24790    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
24791    /// while executing the actual API request.
24792    ///
24793    /// ````text
24794    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
24795    /// ````
24796    ///
24797    /// Sets the *delegate* property to the given value.
24798    pub fn delegate(
24799        mut self,
24800        new_value: &'a mut dyn common::Delegate,
24801    ) -> UserSettingUpdateAutoForwardingCall<'a, C> {
24802        self._delegate = Some(new_value);
24803        self
24804    }
24805
24806    /// Set any additional parameter of the query string used in the request.
24807    /// It should be used to set parameters which are not yet available through their own
24808    /// setters.
24809    ///
24810    /// Please note that this method must not be used to set any of the known parameters
24811    /// which have their own setter method. If done anyway, the request will fail.
24812    ///
24813    /// # Additional Parameters
24814    ///
24815    /// * *$.xgafv* (query-string) - V1 error format.
24816    /// * *access_token* (query-string) - OAuth access token.
24817    /// * *alt* (query-string) - Data format for response.
24818    /// * *callback* (query-string) - JSONP
24819    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
24820    /// * *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.
24821    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
24822    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
24823    /// * *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.
24824    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
24825    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
24826    pub fn param<T>(mut self, name: T, value: T) -> UserSettingUpdateAutoForwardingCall<'a, C>
24827    where
24828        T: AsRef<str>,
24829    {
24830        self._additional_params
24831            .insert(name.as_ref().to_string(), value.as_ref().to_string());
24832        self
24833    }
24834
24835    /// Identifies the authorization scope for the method you are building.
24836    ///
24837    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
24838    /// [`Scope::SettingSharing`].
24839    ///
24840    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
24841    /// tokens for more than one scope.
24842    ///
24843    /// Usually there is more than one suitable scope to authorize an operation, some of which may
24844    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
24845    /// sufficient, a read-write scope will do as well.
24846    pub fn add_scope<St>(mut self, scope: St) -> UserSettingUpdateAutoForwardingCall<'a, C>
24847    where
24848        St: AsRef<str>,
24849    {
24850        self._scopes.insert(String::from(scope.as_ref()));
24851        self
24852    }
24853    /// Identifies the authorization scope(s) for the method you are building.
24854    ///
24855    /// See [`Self::add_scope()`] for details.
24856    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingUpdateAutoForwardingCall<'a, C>
24857    where
24858        I: IntoIterator<Item = St>,
24859        St: AsRef<str>,
24860    {
24861        self._scopes
24862            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
24863        self
24864    }
24865
24866    /// Removes all scopes, and no default scope will be used either.
24867    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
24868    /// for details).
24869    pub fn clear_scopes(mut self) -> UserSettingUpdateAutoForwardingCall<'a, C> {
24870        self._scopes.clear();
24871        self
24872    }
24873}
24874
24875/// Updates IMAP settings.
24876///
24877/// A builder for the *settings.updateImap* method supported by a *user* resource.
24878/// It is not used directly, but through a [`UserMethods`] instance.
24879///
24880/// # Example
24881///
24882/// Instantiate a resource method builder
24883///
24884/// ```test_harness,no_run
24885/// # extern crate hyper;
24886/// # extern crate hyper_rustls;
24887/// # extern crate google_gmail1 as gmail1;
24888/// use gmail1::api::ImapSettings;
24889/// # async fn dox() {
24890/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
24891///
24892/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
24893/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
24894/// #     secret,
24895/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
24896/// # ).build().await.unwrap();
24897///
24898/// # let client = hyper_util::client::legacy::Client::builder(
24899/// #     hyper_util::rt::TokioExecutor::new()
24900/// # )
24901/// # .build(
24902/// #     hyper_rustls::HttpsConnectorBuilder::new()
24903/// #         .with_native_roots()
24904/// #         .unwrap()
24905/// #         .https_or_http()
24906/// #         .enable_http1()
24907/// #         .build()
24908/// # );
24909/// # let mut hub = Gmail::new(client, auth);
24910/// // As the method needs a request, you would usually fill it with the desired information
24911/// // into the respective structure. Some of the parts shown here might not be applicable !
24912/// // Values shown here are possibly random and not representative !
24913/// let mut req = ImapSettings::default();
24914///
24915/// // You can configure optional parameters by calling the respective setters at will, and
24916/// // execute the final call using `doit()`.
24917/// // Values shown here are possibly random and not representative !
24918/// let result = hub.users().settings_update_imap(req, "userId")
24919///              .doit().await;
24920/// # }
24921/// ```
24922pub struct UserSettingUpdateImapCall<'a, C>
24923where
24924    C: 'a,
24925{
24926    hub: &'a Gmail<C>,
24927    _request: ImapSettings,
24928    _user_id: String,
24929    _delegate: Option<&'a mut dyn common::Delegate>,
24930    _additional_params: HashMap<String, String>,
24931    _scopes: BTreeSet<String>,
24932}
24933
24934impl<'a, C> common::CallBuilder for UserSettingUpdateImapCall<'a, C> {}
24935
24936impl<'a, C> UserSettingUpdateImapCall<'a, C>
24937where
24938    C: common::Connector,
24939{
24940    /// Perform the operation you have build so far.
24941    pub async fn doit(mut self) -> common::Result<(common::Response, ImapSettings)> {
24942        use std::borrow::Cow;
24943        use std::io::{Read, Seek};
24944
24945        use common::{url::Params, ToParts};
24946        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
24947
24948        let mut dd = common::DefaultDelegate;
24949        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
24950        dlg.begin(common::MethodInfo {
24951            id: "gmail.users.settings.updateImap",
24952            http_method: hyper::Method::PUT,
24953        });
24954
24955        for &field in ["alt", "userId"].iter() {
24956            if self._additional_params.contains_key(field) {
24957                dlg.finished(false);
24958                return Err(common::Error::FieldClash(field));
24959            }
24960        }
24961
24962        let mut params = Params::with_capacity(4 + self._additional_params.len());
24963        params.push("userId", self._user_id);
24964
24965        params.extend(self._additional_params.iter());
24966
24967        params.push("alt", "json");
24968        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/imap";
24969        if self._scopes.is_empty() {
24970            self._scopes
24971                .insert(Scope::SettingBasic.as_ref().to_string());
24972        }
24973
24974        #[allow(clippy::single_element_loop)]
24975        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
24976            url = params.uri_replacement(url, param_name, find_this, false);
24977        }
24978        {
24979            let to_remove = ["userId"];
24980            params.remove_params(&to_remove);
24981        }
24982
24983        let url = params.parse_with_url(&url);
24984
24985        let mut json_mime_type = mime::APPLICATION_JSON;
24986        let mut request_value_reader = {
24987            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
24988            common::remove_json_null_values(&mut value);
24989            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
24990            serde_json::to_writer(&mut dst, &value).unwrap();
24991            dst
24992        };
24993        let request_size = request_value_reader
24994            .seek(std::io::SeekFrom::End(0))
24995            .unwrap();
24996        request_value_reader
24997            .seek(std::io::SeekFrom::Start(0))
24998            .unwrap();
24999
25000        loop {
25001            let token = match self
25002                .hub
25003                .auth
25004                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
25005                .await
25006            {
25007                Ok(token) => token,
25008                Err(e) => match dlg.token(e) {
25009                    Ok(token) => token,
25010                    Err(e) => {
25011                        dlg.finished(false);
25012                        return Err(common::Error::MissingToken(e));
25013                    }
25014                },
25015            };
25016            request_value_reader
25017                .seek(std::io::SeekFrom::Start(0))
25018                .unwrap();
25019            let mut req_result = {
25020                let client = &self.hub.client;
25021                dlg.pre_request();
25022                let mut req_builder = hyper::Request::builder()
25023                    .method(hyper::Method::PUT)
25024                    .uri(url.as_str())
25025                    .header(USER_AGENT, self.hub._user_agent.clone());
25026
25027                if let Some(token) = token.as_ref() {
25028                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
25029                }
25030
25031                let request = req_builder
25032                    .header(CONTENT_TYPE, json_mime_type.to_string())
25033                    .header(CONTENT_LENGTH, request_size as u64)
25034                    .body(common::to_body(
25035                        request_value_reader.get_ref().clone().into(),
25036                    ));
25037
25038                client.request(request.unwrap()).await
25039            };
25040
25041            match req_result {
25042                Err(err) => {
25043                    if let common::Retry::After(d) = dlg.http_error(&err) {
25044                        sleep(d).await;
25045                        continue;
25046                    }
25047                    dlg.finished(false);
25048                    return Err(common::Error::HttpError(err));
25049                }
25050                Ok(res) => {
25051                    let (mut parts, body) = res.into_parts();
25052                    let mut body = common::Body::new(body);
25053                    if !parts.status.is_success() {
25054                        let bytes = common::to_bytes(body).await.unwrap_or_default();
25055                        let error = serde_json::from_str(&common::to_string(&bytes));
25056                        let response = common::to_response(parts, bytes.into());
25057
25058                        if let common::Retry::After(d) =
25059                            dlg.http_failure(&response, error.as_ref().ok())
25060                        {
25061                            sleep(d).await;
25062                            continue;
25063                        }
25064
25065                        dlg.finished(false);
25066
25067                        return Err(match error {
25068                            Ok(value) => common::Error::BadRequest(value),
25069                            _ => common::Error::Failure(response),
25070                        });
25071                    }
25072                    let response = {
25073                        let bytes = common::to_bytes(body).await.unwrap_or_default();
25074                        let encoded = common::to_string(&bytes);
25075                        match serde_json::from_str(&encoded) {
25076                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
25077                            Err(error) => {
25078                                dlg.response_json_decode_error(&encoded, &error);
25079                                return Err(common::Error::JsonDecodeError(
25080                                    encoded.to_string(),
25081                                    error,
25082                                ));
25083                            }
25084                        }
25085                    };
25086
25087                    dlg.finished(true);
25088                    return Ok(response);
25089                }
25090            }
25091        }
25092    }
25093
25094    ///
25095    /// Sets the *request* property to the given value.
25096    ///
25097    /// Even though the property as already been set when instantiating this call,
25098    /// we provide this method for API completeness.
25099    pub fn request(mut self, new_value: ImapSettings) -> UserSettingUpdateImapCall<'a, C> {
25100        self._request = new_value;
25101        self
25102    }
25103    /// User's email address. The special value "me" can be used to indicate the authenticated user.
25104    ///
25105    /// Sets the *user id* path property to the given value.
25106    ///
25107    /// Even though the property as already been set when instantiating this call,
25108    /// we provide this method for API completeness.
25109    pub fn user_id(mut self, new_value: &str) -> UserSettingUpdateImapCall<'a, C> {
25110        self._user_id = new_value.to_string();
25111        self
25112    }
25113    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
25114    /// while executing the actual API request.
25115    ///
25116    /// ````text
25117    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
25118    /// ````
25119    ///
25120    /// Sets the *delegate* property to the given value.
25121    pub fn delegate(
25122        mut self,
25123        new_value: &'a mut dyn common::Delegate,
25124    ) -> UserSettingUpdateImapCall<'a, C> {
25125        self._delegate = Some(new_value);
25126        self
25127    }
25128
25129    /// Set any additional parameter of the query string used in the request.
25130    /// It should be used to set parameters which are not yet available through their own
25131    /// setters.
25132    ///
25133    /// Please note that this method must not be used to set any of the known parameters
25134    /// which have their own setter method. If done anyway, the request will fail.
25135    ///
25136    /// # Additional Parameters
25137    ///
25138    /// * *$.xgafv* (query-string) - V1 error format.
25139    /// * *access_token* (query-string) - OAuth access token.
25140    /// * *alt* (query-string) - Data format for response.
25141    /// * *callback* (query-string) - JSONP
25142    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
25143    /// * *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.
25144    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
25145    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
25146    /// * *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.
25147    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
25148    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
25149    pub fn param<T>(mut self, name: T, value: T) -> UserSettingUpdateImapCall<'a, C>
25150    where
25151        T: AsRef<str>,
25152    {
25153        self._additional_params
25154            .insert(name.as_ref().to_string(), value.as_ref().to_string());
25155        self
25156    }
25157
25158    /// Identifies the authorization scope for the method you are building.
25159    ///
25160    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
25161    /// [`Scope::SettingBasic`].
25162    ///
25163    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
25164    /// tokens for more than one scope.
25165    ///
25166    /// Usually there is more than one suitable scope to authorize an operation, some of which may
25167    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
25168    /// sufficient, a read-write scope will do as well.
25169    pub fn add_scope<St>(mut self, scope: St) -> UserSettingUpdateImapCall<'a, C>
25170    where
25171        St: AsRef<str>,
25172    {
25173        self._scopes.insert(String::from(scope.as_ref()));
25174        self
25175    }
25176    /// Identifies the authorization scope(s) for the method you are building.
25177    ///
25178    /// See [`Self::add_scope()`] for details.
25179    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingUpdateImapCall<'a, C>
25180    where
25181        I: IntoIterator<Item = St>,
25182        St: AsRef<str>,
25183    {
25184        self._scopes
25185            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
25186        self
25187    }
25188
25189    /// Removes all scopes, and no default scope will be used either.
25190    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
25191    /// for details).
25192    pub fn clear_scopes(mut self) -> UserSettingUpdateImapCall<'a, C> {
25193        self._scopes.clear();
25194        self
25195    }
25196}
25197
25198/// Updates language settings. If successful, the return object contains the `displayLanguage` that was saved for the user, which may differ from the value passed into the request. This is because the requested `displayLanguage` may not be directly supported by Gmail but have a close variant that is, and so the variant may be chosen and saved instead.
25199///
25200/// A builder for the *settings.updateLanguage* method supported by a *user* resource.
25201/// It is not used directly, but through a [`UserMethods`] instance.
25202///
25203/// # Example
25204///
25205/// Instantiate a resource method builder
25206///
25207/// ```test_harness,no_run
25208/// # extern crate hyper;
25209/// # extern crate hyper_rustls;
25210/// # extern crate google_gmail1 as gmail1;
25211/// use gmail1::api::LanguageSettings;
25212/// # async fn dox() {
25213/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
25214///
25215/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
25216/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
25217/// #     secret,
25218/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
25219/// # ).build().await.unwrap();
25220///
25221/// # let client = hyper_util::client::legacy::Client::builder(
25222/// #     hyper_util::rt::TokioExecutor::new()
25223/// # )
25224/// # .build(
25225/// #     hyper_rustls::HttpsConnectorBuilder::new()
25226/// #         .with_native_roots()
25227/// #         .unwrap()
25228/// #         .https_or_http()
25229/// #         .enable_http1()
25230/// #         .build()
25231/// # );
25232/// # let mut hub = Gmail::new(client, auth);
25233/// // As the method needs a request, you would usually fill it with the desired information
25234/// // into the respective structure. Some of the parts shown here might not be applicable !
25235/// // Values shown here are possibly random and not representative !
25236/// let mut req = LanguageSettings::default();
25237///
25238/// // You can configure optional parameters by calling the respective setters at will, and
25239/// // execute the final call using `doit()`.
25240/// // Values shown here are possibly random and not representative !
25241/// let result = hub.users().settings_update_language(req, "userId")
25242///              .doit().await;
25243/// # }
25244/// ```
25245pub struct UserSettingUpdateLanguageCall<'a, C>
25246where
25247    C: 'a,
25248{
25249    hub: &'a Gmail<C>,
25250    _request: LanguageSettings,
25251    _user_id: String,
25252    _delegate: Option<&'a mut dyn common::Delegate>,
25253    _additional_params: HashMap<String, String>,
25254    _scopes: BTreeSet<String>,
25255}
25256
25257impl<'a, C> common::CallBuilder for UserSettingUpdateLanguageCall<'a, C> {}
25258
25259impl<'a, C> UserSettingUpdateLanguageCall<'a, C>
25260where
25261    C: common::Connector,
25262{
25263    /// Perform the operation you have build so far.
25264    pub async fn doit(mut self) -> common::Result<(common::Response, LanguageSettings)> {
25265        use std::borrow::Cow;
25266        use std::io::{Read, Seek};
25267
25268        use common::{url::Params, ToParts};
25269        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
25270
25271        let mut dd = common::DefaultDelegate;
25272        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
25273        dlg.begin(common::MethodInfo {
25274            id: "gmail.users.settings.updateLanguage",
25275            http_method: hyper::Method::PUT,
25276        });
25277
25278        for &field in ["alt", "userId"].iter() {
25279            if self._additional_params.contains_key(field) {
25280                dlg.finished(false);
25281                return Err(common::Error::FieldClash(field));
25282            }
25283        }
25284
25285        let mut params = Params::with_capacity(4 + self._additional_params.len());
25286        params.push("userId", self._user_id);
25287
25288        params.extend(self._additional_params.iter());
25289
25290        params.push("alt", "json");
25291        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/language";
25292        if self._scopes.is_empty() {
25293            self._scopes
25294                .insert(Scope::SettingBasic.as_ref().to_string());
25295        }
25296
25297        #[allow(clippy::single_element_loop)]
25298        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
25299            url = params.uri_replacement(url, param_name, find_this, false);
25300        }
25301        {
25302            let to_remove = ["userId"];
25303            params.remove_params(&to_remove);
25304        }
25305
25306        let url = params.parse_with_url(&url);
25307
25308        let mut json_mime_type = mime::APPLICATION_JSON;
25309        let mut request_value_reader = {
25310            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
25311            common::remove_json_null_values(&mut value);
25312            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
25313            serde_json::to_writer(&mut dst, &value).unwrap();
25314            dst
25315        };
25316        let request_size = request_value_reader
25317            .seek(std::io::SeekFrom::End(0))
25318            .unwrap();
25319        request_value_reader
25320            .seek(std::io::SeekFrom::Start(0))
25321            .unwrap();
25322
25323        loop {
25324            let token = match self
25325                .hub
25326                .auth
25327                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
25328                .await
25329            {
25330                Ok(token) => token,
25331                Err(e) => match dlg.token(e) {
25332                    Ok(token) => token,
25333                    Err(e) => {
25334                        dlg.finished(false);
25335                        return Err(common::Error::MissingToken(e));
25336                    }
25337                },
25338            };
25339            request_value_reader
25340                .seek(std::io::SeekFrom::Start(0))
25341                .unwrap();
25342            let mut req_result = {
25343                let client = &self.hub.client;
25344                dlg.pre_request();
25345                let mut req_builder = hyper::Request::builder()
25346                    .method(hyper::Method::PUT)
25347                    .uri(url.as_str())
25348                    .header(USER_AGENT, self.hub._user_agent.clone());
25349
25350                if let Some(token) = token.as_ref() {
25351                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
25352                }
25353
25354                let request = req_builder
25355                    .header(CONTENT_TYPE, json_mime_type.to_string())
25356                    .header(CONTENT_LENGTH, request_size as u64)
25357                    .body(common::to_body(
25358                        request_value_reader.get_ref().clone().into(),
25359                    ));
25360
25361                client.request(request.unwrap()).await
25362            };
25363
25364            match req_result {
25365                Err(err) => {
25366                    if let common::Retry::After(d) = dlg.http_error(&err) {
25367                        sleep(d).await;
25368                        continue;
25369                    }
25370                    dlg.finished(false);
25371                    return Err(common::Error::HttpError(err));
25372                }
25373                Ok(res) => {
25374                    let (mut parts, body) = res.into_parts();
25375                    let mut body = common::Body::new(body);
25376                    if !parts.status.is_success() {
25377                        let bytes = common::to_bytes(body).await.unwrap_or_default();
25378                        let error = serde_json::from_str(&common::to_string(&bytes));
25379                        let response = common::to_response(parts, bytes.into());
25380
25381                        if let common::Retry::After(d) =
25382                            dlg.http_failure(&response, error.as_ref().ok())
25383                        {
25384                            sleep(d).await;
25385                            continue;
25386                        }
25387
25388                        dlg.finished(false);
25389
25390                        return Err(match error {
25391                            Ok(value) => common::Error::BadRequest(value),
25392                            _ => common::Error::Failure(response),
25393                        });
25394                    }
25395                    let response = {
25396                        let bytes = common::to_bytes(body).await.unwrap_or_default();
25397                        let encoded = common::to_string(&bytes);
25398                        match serde_json::from_str(&encoded) {
25399                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
25400                            Err(error) => {
25401                                dlg.response_json_decode_error(&encoded, &error);
25402                                return Err(common::Error::JsonDecodeError(
25403                                    encoded.to_string(),
25404                                    error,
25405                                ));
25406                            }
25407                        }
25408                    };
25409
25410                    dlg.finished(true);
25411                    return Ok(response);
25412                }
25413            }
25414        }
25415    }
25416
25417    ///
25418    /// Sets the *request* property to the given value.
25419    ///
25420    /// Even though the property as already been set when instantiating this call,
25421    /// we provide this method for API completeness.
25422    pub fn request(mut self, new_value: LanguageSettings) -> UserSettingUpdateLanguageCall<'a, C> {
25423        self._request = new_value;
25424        self
25425    }
25426    /// User's email address. The special value "me" can be used to indicate the authenticated user.
25427    ///
25428    /// Sets the *user id* path property to the given value.
25429    ///
25430    /// Even though the property as already been set when instantiating this call,
25431    /// we provide this method for API completeness.
25432    pub fn user_id(mut self, new_value: &str) -> UserSettingUpdateLanguageCall<'a, C> {
25433        self._user_id = new_value.to_string();
25434        self
25435    }
25436    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
25437    /// while executing the actual API request.
25438    ///
25439    /// ````text
25440    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
25441    /// ````
25442    ///
25443    /// Sets the *delegate* property to the given value.
25444    pub fn delegate(
25445        mut self,
25446        new_value: &'a mut dyn common::Delegate,
25447    ) -> UserSettingUpdateLanguageCall<'a, C> {
25448        self._delegate = Some(new_value);
25449        self
25450    }
25451
25452    /// Set any additional parameter of the query string used in the request.
25453    /// It should be used to set parameters which are not yet available through their own
25454    /// setters.
25455    ///
25456    /// Please note that this method must not be used to set any of the known parameters
25457    /// which have their own setter method. If done anyway, the request will fail.
25458    ///
25459    /// # Additional Parameters
25460    ///
25461    /// * *$.xgafv* (query-string) - V1 error format.
25462    /// * *access_token* (query-string) - OAuth access token.
25463    /// * *alt* (query-string) - Data format for response.
25464    /// * *callback* (query-string) - JSONP
25465    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
25466    /// * *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.
25467    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
25468    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
25469    /// * *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.
25470    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
25471    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
25472    pub fn param<T>(mut self, name: T, value: T) -> UserSettingUpdateLanguageCall<'a, C>
25473    where
25474        T: AsRef<str>,
25475    {
25476        self._additional_params
25477            .insert(name.as_ref().to_string(), value.as_ref().to_string());
25478        self
25479    }
25480
25481    /// Identifies the authorization scope for the method you are building.
25482    ///
25483    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
25484    /// [`Scope::SettingBasic`].
25485    ///
25486    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
25487    /// tokens for more than one scope.
25488    ///
25489    /// Usually there is more than one suitable scope to authorize an operation, some of which may
25490    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
25491    /// sufficient, a read-write scope will do as well.
25492    pub fn add_scope<St>(mut self, scope: St) -> UserSettingUpdateLanguageCall<'a, C>
25493    where
25494        St: AsRef<str>,
25495    {
25496        self._scopes.insert(String::from(scope.as_ref()));
25497        self
25498    }
25499    /// Identifies the authorization scope(s) for the method you are building.
25500    ///
25501    /// See [`Self::add_scope()`] for details.
25502    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingUpdateLanguageCall<'a, C>
25503    where
25504        I: IntoIterator<Item = St>,
25505        St: AsRef<str>,
25506    {
25507        self._scopes
25508            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
25509        self
25510    }
25511
25512    /// Removes all scopes, and no default scope will be used either.
25513    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
25514    /// for details).
25515    pub fn clear_scopes(mut self) -> UserSettingUpdateLanguageCall<'a, C> {
25516        self._scopes.clear();
25517        self
25518    }
25519}
25520
25521/// Updates POP settings.
25522///
25523/// A builder for the *settings.updatePop* method supported by a *user* resource.
25524/// It is not used directly, but through a [`UserMethods`] instance.
25525///
25526/// # Example
25527///
25528/// Instantiate a resource method builder
25529///
25530/// ```test_harness,no_run
25531/// # extern crate hyper;
25532/// # extern crate hyper_rustls;
25533/// # extern crate google_gmail1 as gmail1;
25534/// use gmail1::api::PopSettings;
25535/// # async fn dox() {
25536/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
25537///
25538/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
25539/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
25540/// #     secret,
25541/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
25542/// # ).build().await.unwrap();
25543///
25544/// # let client = hyper_util::client::legacy::Client::builder(
25545/// #     hyper_util::rt::TokioExecutor::new()
25546/// # )
25547/// # .build(
25548/// #     hyper_rustls::HttpsConnectorBuilder::new()
25549/// #         .with_native_roots()
25550/// #         .unwrap()
25551/// #         .https_or_http()
25552/// #         .enable_http1()
25553/// #         .build()
25554/// # );
25555/// # let mut hub = Gmail::new(client, auth);
25556/// // As the method needs a request, you would usually fill it with the desired information
25557/// // into the respective structure. Some of the parts shown here might not be applicable !
25558/// // Values shown here are possibly random and not representative !
25559/// let mut req = PopSettings::default();
25560///
25561/// // You can configure optional parameters by calling the respective setters at will, and
25562/// // execute the final call using `doit()`.
25563/// // Values shown here are possibly random and not representative !
25564/// let result = hub.users().settings_update_pop(req, "userId")
25565///              .doit().await;
25566/// # }
25567/// ```
25568pub struct UserSettingUpdatePopCall<'a, C>
25569where
25570    C: 'a,
25571{
25572    hub: &'a Gmail<C>,
25573    _request: PopSettings,
25574    _user_id: String,
25575    _delegate: Option<&'a mut dyn common::Delegate>,
25576    _additional_params: HashMap<String, String>,
25577    _scopes: BTreeSet<String>,
25578}
25579
25580impl<'a, C> common::CallBuilder for UserSettingUpdatePopCall<'a, C> {}
25581
25582impl<'a, C> UserSettingUpdatePopCall<'a, C>
25583where
25584    C: common::Connector,
25585{
25586    /// Perform the operation you have build so far.
25587    pub async fn doit(mut self) -> common::Result<(common::Response, PopSettings)> {
25588        use std::borrow::Cow;
25589        use std::io::{Read, Seek};
25590
25591        use common::{url::Params, ToParts};
25592        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
25593
25594        let mut dd = common::DefaultDelegate;
25595        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
25596        dlg.begin(common::MethodInfo {
25597            id: "gmail.users.settings.updatePop",
25598            http_method: hyper::Method::PUT,
25599        });
25600
25601        for &field in ["alt", "userId"].iter() {
25602            if self._additional_params.contains_key(field) {
25603                dlg.finished(false);
25604                return Err(common::Error::FieldClash(field));
25605            }
25606        }
25607
25608        let mut params = Params::with_capacity(4 + self._additional_params.len());
25609        params.push("userId", self._user_id);
25610
25611        params.extend(self._additional_params.iter());
25612
25613        params.push("alt", "json");
25614        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/pop";
25615        if self._scopes.is_empty() {
25616            self._scopes
25617                .insert(Scope::SettingBasic.as_ref().to_string());
25618        }
25619
25620        #[allow(clippy::single_element_loop)]
25621        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
25622            url = params.uri_replacement(url, param_name, find_this, false);
25623        }
25624        {
25625            let to_remove = ["userId"];
25626            params.remove_params(&to_remove);
25627        }
25628
25629        let url = params.parse_with_url(&url);
25630
25631        let mut json_mime_type = mime::APPLICATION_JSON;
25632        let mut request_value_reader = {
25633            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
25634            common::remove_json_null_values(&mut value);
25635            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
25636            serde_json::to_writer(&mut dst, &value).unwrap();
25637            dst
25638        };
25639        let request_size = request_value_reader
25640            .seek(std::io::SeekFrom::End(0))
25641            .unwrap();
25642        request_value_reader
25643            .seek(std::io::SeekFrom::Start(0))
25644            .unwrap();
25645
25646        loop {
25647            let token = match self
25648                .hub
25649                .auth
25650                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
25651                .await
25652            {
25653                Ok(token) => token,
25654                Err(e) => match dlg.token(e) {
25655                    Ok(token) => token,
25656                    Err(e) => {
25657                        dlg.finished(false);
25658                        return Err(common::Error::MissingToken(e));
25659                    }
25660                },
25661            };
25662            request_value_reader
25663                .seek(std::io::SeekFrom::Start(0))
25664                .unwrap();
25665            let mut req_result = {
25666                let client = &self.hub.client;
25667                dlg.pre_request();
25668                let mut req_builder = hyper::Request::builder()
25669                    .method(hyper::Method::PUT)
25670                    .uri(url.as_str())
25671                    .header(USER_AGENT, self.hub._user_agent.clone());
25672
25673                if let Some(token) = token.as_ref() {
25674                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
25675                }
25676
25677                let request = req_builder
25678                    .header(CONTENT_TYPE, json_mime_type.to_string())
25679                    .header(CONTENT_LENGTH, request_size as u64)
25680                    .body(common::to_body(
25681                        request_value_reader.get_ref().clone().into(),
25682                    ));
25683
25684                client.request(request.unwrap()).await
25685            };
25686
25687            match req_result {
25688                Err(err) => {
25689                    if let common::Retry::After(d) = dlg.http_error(&err) {
25690                        sleep(d).await;
25691                        continue;
25692                    }
25693                    dlg.finished(false);
25694                    return Err(common::Error::HttpError(err));
25695                }
25696                Ok(res) => {
25697                    let (mut parts, body) = res.into_parts();
25698                    let mut body = common::Body::new(body);
25699                    if !parts.status.is_success() {
25700                        let bytes = common::to_bytes(body).await.unwrap_or_default();
25701                        let error = serde_json::from_str(&common::to_string(&bytes));
25702                        let response = common::to_response(parts, bytes.into());
25703
25704                        if let common::Retry::After(d) =
25705                            dlg.http_failure(&response, error.as_ref().ok())
25706                        {
25707                            sleep(d).await;
25708                            continue;
25709                        }
25710
25711                        dlg.finished(false);
25712
25713                        return Err(match error {
25714                            Ok(value) => common::Error::BadRequest(value),
25715                            _ => common::Error::Failure(response),
25716                        });
25717                    }
25718                    let response = {
25719                        let bytes = common::to_bytes(body).await.unwrap_or_default();
25720                        let encoded = common::to_string(&bytes);
25721                        match serde_json::from_str(&encoded) {
25722                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
25723                            Err(error) => {
25724                                dlg.response_json_decode_error(&encoded, &error);
25725                                return Err(common::Error::JsonDecodeError(
25726                                    encoded.to_string(),
25727                                    error,
25728                                ));
25729                            }
25730                        }
25731                    };
25732
25733                    dlg.finished(true);
25734                    return Ok(response);
25735                }
25736            }
25737        }
25738    }
25739
25740    ///
25741    /// Sets the *request* property to the given value.
25742    ///
25743    /// Even though the property as already been set when instantiating this call,
25744    /// we provide this method for API completeness.
25745    pub fn request(mut self, new_value: PopSettings) -> UserSettingUpdatePopCall<'a, C> {
25746        self._request = new_value;
25747        self
25748    }
25749    /// User's email address. The special value "me" can be used to indicate the authenticated user.
25750    ///
25751    /// Sets the *user id* path property to the given value.
25752    ///
25753    /// Even though the property as already been set when instantiating this call,
25754    /// we provide this method for API completeness.
25755    pub fn user_id(mut self, new_value: &str) -> UserSettingUpdatePopCall<'a, C> {
25756        self._user_id = new_value.to_string();
25757        self
25758    }
25759    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
25760    /// while executing the actual API request.
25761    ///
25762    /// ````text
25763    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
25764    /// ````
25765    ///
25766    /// Sets the *delegate* property to the given value.
25767    pub fn delegate(
25768        mut self,
25769        new_value: &'a mut dyn common::Delegate,
25770    ) -> UserSettingUpdatePopCall<'a, C> {
25771        self._delegate = Some(new_value);
25772        self
25773    }
25774
25775    /// Set any additional parameter of the query string used in the request.
25776    /// It should be used to set parameters which are not yet available through their own
25777    /// setters.
25778    ///
25779    /// Please note that this method must not be used to set any of the known parameters
25780    /// which have their own setter method. If done anyway, the request will fail.
25781    ///
25782    /// # Additional Parameters
25783    ///
25784    /// * *$.xgafv* (query-string) - V1 error format.
25785    /// * *access_token* (query-string) - OAuth access token.
25786    /// * *alt* (query-string) - Data format for response.
25787    /// * *callback* (query-string) - JSONP
25788    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
25789    /// * *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.
25790    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
25791    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
25792    /// * *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.
25793    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
25794    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
25795    pub fn param<T>(mut self, name: T, value: T) -> UserSettingUpdatePopCall<'a, C>
25796    where
25797        T: AsRef<str>,
25798    {
25799        self._additional_params
25800            .insert(name.as_ref().to_string(), value.as_ref().to_string());
25801        self
25802    }
25803
25804    /// Identifies the authorization scope for the method you are building.
25805    ///
25806    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
25807    /// [`Scope::SettingBasic`].
25808    ///
25809    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
25810    /// tokens for more than one scope.
25811    ///
25812    /// Usually there is more than one suitable scope to authorize an operation, some of which may
25813    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
25814    /// sufficient, a read-write scope will do as well.
25815    pub fn add_scope<St>(mut self, scope: St) -> UserSettingUpdatePopCall<'a, C>
25816    where
25817        St: AsRef<str>,
25818    {
25819        self._scopes.insert(String::from(scope.as_ref()));
25820        self
25821    }
25822    /// Identifies the authorization scope(s) for the method you are building.
25823    ///
25824    /// See [`Self::add_scope()`] for details.
25825    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingUpdatePopCall<'a, C>
25826    where
25827        I: IntoIterator<Item = St>,
25828        St: AsRef<str>,
25829    {
25830        self._scopes
25831            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
25832        self
25833    }
25834
25835    /// Removes all scopes, and no default scope will be used either.
25836    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
25837    /// for details).
25838    pub fn clear_scopes(mut self) -> UserSettingUpdatePopCall<'a, C> {
25839        self._scopes.clear();
25840        self
25841    }
25842}
25843
25844/// Updates vacation responder settings.
25845///
25846/// A builder for the *settings.updateVacation* method supported by a *user* resource.
25847/// It is not used directly, but through a [`UserMethods`] instance.
25848///
25849/// # Example
25850///
25851/// Instantiate a resource method builder
25852///
25853/// ```test_harness,no_run
25854/// # extern crate hyper;
25855/// # extern crate hyper_rustls;
25856/// # extern crate google_gmail1 as gmail1;
25857/// use gmail1::api::VacationSettings;
25858/// # async fn dox() {
25859/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
25860///
25861/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
25862/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
25863/// #     secret,
25864/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
25865/// # ).build().await.unwrap();
25866///
25867/// # let client = hyper_util::client::legacy::Client::builder(
25868/// #     hyper_util::rt::TokioExecutor::new()
25869/// # )
25870/// # .build(
25871/// #     hyper_rustls::HttpsConnectorBuilder::new()
25872/// #         .with_native_roots()
25873/// #         .unwrap()
25874/// #         .https_or_http()
25875/// #         .enable_http1()
25876/// #         .build()
25877/// # );
25878/// # let mut hub = Gmail::new(client, auth);
25879/// // As the method needs a request, you would usually fill it with the desired information
25880/// // into the respective structure. Some of the parts shown here might not be applicable !
25881/// // Values shown here are possibly random and not representative !
25882/// let mut req = VacationSettings::default();
25883///
25884/// // You can configure optional parameters by calling the respective setters at will, and
25885/// // execute the final call using `doit()`.
25886/// // Values shown here are possibly random and not representative !
25887/// let result = hub.users().settings_update_vacation(req, "userId")
25888///              .doit().await;
25889/// # }
25890/// ```
25891pub struct UserSettingUpdateVacationCall<'a, C>
25892where
25893    C: 'a,
25894{
25895    hub: &'a Gmail<C>,
25896    _request: VacationSettings,
25897    _user_id: String,
25898    _delegate: Option<&'a mut dyn common::Delegate>,
25899    _additional_params: HashMap<String, String>,
25900    _scopes: BTreeSet<String>,
25901}
25902
25903impl<'a, C> common::CallBuilder for UserSettingUpdateVacationCall<'a, C> {}
25904
25905impl<'a, C> UserSettingUpdateVacationCall<'a, C>
25906where
25907    C: common::Connector,
25908{
25909    /// Perform the operation you have build so far.
25910    pub async fn doit(mut self) -> common::Result<(common::Response, VacationSettings)> {
25911        use std::borrow::Cow;
25912        use std::io::{Read, Seek};
25913
25914        use common::{url::Params, ToParts};
25915        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
25916
25917        let mut dd = common::DefaultDelegate;
25918        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
25919        dlg.begin(common::MethodInfo {
25920            id: "gmail.users.settings.updateVacation",
25921            http_method: hyper::Method::PUT,
25922        });
25923
25924        for &field in ["alt", "userId"].iter() {
25925            if self._additional_params.contains_key(field) {
25926                dlg.finished(false);
25927                return Err(common::Error::FieldClash(field));
25928            }
25929        }
25930
25931        let mut params = Params::with_capacity(4 + self._additional_params.len());
25932        params.push("userId", self._user_id);
25933
25934        params.extend(self._additional_params.iter());
25935
25936        params.push("alt", "json");
25937        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/settings/vacation";
25938        if self._scopes.is_empty() {
25939            self._scopes
25940                .insert(Scope::SettingBasic.as_ref().to_string());
25941        }
25942
25943        #[allow(clippy::single_element_loop)]
25944        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
25945            url = params.uri_replacement(url, param_name, find_this, false);
25946        }
25947        {
25948            let to_remove = ["userId"];
25949            params.remove_params(&to_remove);
25950        }
25951
25952        let url = params.parse_with_url(&url);
25953
25954        let mut json_mime_type = mime::APPLICATION_JSON;
25955        let mut request_value_reader = {
25956            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
25957            common::remove_json_null_values(&mut value);
25958            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
25959            serde_json::to_writer(&mut dst, &value).unwrap();
25960            dst
25961        };
25962        let request_size = request_value_reader
25963            .seek(std::io::SeekFrom::End(0))
25964            .unwrap();
25965        request_value_reader
25966            .seek(std::io::SeekFrom::Start(0))
25967            .unwrap();
25968
25969        loop {
25970            let token = match self
25971                .hub
25972                .auth
25973                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
25974                .await
25975            {
25976                Ok(token) => token,
25977                Err(e) => match dlg.token(e) {
25978                    Ok(token) => token,
25979                    Err(e) => {
25980                        dlg.finished(false);
25981                        return Err(common::Error::MissingToken(e));
25982                    }
25983                },
25984            };
25985            request_value_reader
25986                .seek(std::io::SeekFrom::Start(0))
25987                .unwrap();
25988            let mut req_result = {
25989                let client = &self.hub.client;
25990                dlg.pre_request();
25991                let mut req_builder = hyper::Request::builder()
25992                    .method(hyper::Method::PUT)
25993                    .uri(url.as_str())
25994                    .header(USER_AGENT, self.hub._user_agent.clone());
25995
25996                if let Some(token) = token.as_ref() {
25997                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
25998                }
25999
26000                let request = req_builder
26001                    .header(CONTENT_TYPE, json_mime_type.to_string())
26002                    .header(CONTENT_LENGTH, request_size as u64)
26003                    .body(common::to_body(
26004                        request_value_reader.get_ref().clone().into(),
26005                    ));
26006
26007                client.request(request.unwrap()).await
26008            };
26009
26010            match req_result {
26011                Err(err) => {
26012                    if let common::Retry::After(d) = dlg.http_error(&err) {
26013                        sleep(d).await;
26014                        continue;
26015                    }
26016                    dlg.finished(false);
26017                    return Err(common::Error::HttpError(err));
26018                }
26019                Ok(res) => {
26020                    let (mut parts, body) = res.into_parts();
26021                    let mut body = common::Body::new(body);
26022                    if !parts.status.is_success() {
26023                        let bytes = common::to_bytes(body).await.unwrap_or_default();
26024                        let error = serde_json::from_str(&common::to_string(&bytes));
26025                        let response = common::to_response(parts, bytes.into());
26026
26027                        if let common::Retry::After(d) =
26028                            dlg.http_failure(&response, error.as_ref().ok())
26029                        {
26030                            sleep(d).await;
26031                            continue;
26032                        }
26033
26034                        dlg.finished(false);
26035
26036                        return Err(match error {
26037                            Ok(value) => common::Error::BadRequest(value),
26038                            _ => common::Error::Failure(response),
26039                        });
26040                    }
26041                    let response = {
26042                        let bytes = common::to_bytes(body).await.unwrap_or_default();
26043                        let encoded = common::to_string(&bytes);
26044                        match serde_json::from_str(&encoded) {
26045                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
26046                            Err(error) => {
26047                                dlg.response_json_decode_error(&encoded, &error);
26048                                return Err(common::Error::JsonDecodeError(
26049                                    encoded.to_string(),
26050                                    error,
26051                                ));
26052                            }
26053                        }
26054                    };
26055
26056                    dlg.finished(true);
26057                    return Ok(response);
26058                }
26059            }
26060        }
26061    }
26062
26063    ///
26064    /// Sets the *request* property to the given value.
26065    ///
26066    /// Even though the property as already been set when instantiating this call,
26067    /// we provide this method for API completeness.
26068    pub fn request(mut self, new_value: VacationSettings) -> UserSettingUpdateVacationCall<'a, C> {
26069        self._request = new_value;
26070        self
26071    }
26072    /// User's email address. The special value "me" can be used to indicate the authenticated user.
26073    ///
26074    /// Sets the *user id* path property to the given value.
26075    ///
26076    /// Even though the property as already been set when instantiating this call,
26077    /// we provide this method for API completeness.
26078    pub fn user_id(mut self, new_value: &str) -> UserSettingUpdateVacationCall<'a, C> {
26079        self._user_id = new_value.to_string();
26080        self
26081    }
26082    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
26083    /// while executing the actual API request.
26084    ///
26085    /// ````text
26086    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
26087    /// ````
26088    ///
26089    /// Sets the *delegate* property to the given value.
26090    pub fn delegate(
26091        mut self,
26092        new_value: &'a mut dyn common::Delegate,
26093    ) -> UserSettingUpdateVacationCall<'a, C> {
26094        self._delegate = Some(new_value);
26095        self
26096    }
26097
26098    /// Set any additional parameter of the query string used in the request.
26099    /// It should be used to set parameters which are not yet available through their own
26100    /// setters.
26101    ///
26102    /// Please note that this method must not be used to set any of the known parameters
26103    /// which have their own setter method. If done anyway, the request will fail.
26104    ///
26105    /// # Additional Parameters
26106    ///
26107    /// * *$.xgafv* (query-string) - V1 error format.
26108    /// * *access_token* (query-string) - OAuth access token.
26109    /// * *alt* (query-string) - Data format for response.
26110    /// * *callback* (query-string) - JSONP
26111    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
26112    /// * *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.
26113    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
26114    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
26115    /// * *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.
26116    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
26117    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
26118    pub fn param<T>(mut self, name: T, value: T) -> UserSettingUpdateVacationCall<'a, C>
26119    where
26120        T: AsRef<str>,
26121    {
26122        self._additional_params
26123            .insert(name.as_ref().to_string(), value.as_ref().to_string());
26124        self
26125    }
26126
26127    /// Identifies the authorization scope for the method you are building.
26128    ///
26129    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
26130    /// [`Scope::SettingBasic`].
26131    ///
26132    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
26133    /// tokens for more than one scope.
26134    ///
26135    /// Usually there is more than one suitable scope to authorize an operation, some of which may
26136    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
26137    /// sufficient, a read-write scope will do as well.
26138    pub fn add_scope<St>(mut self, scope: St) -> UserSettingUpdateVacationCall<'a, C>
26139    where
26140        St: AsRef<str>,
26141    {
26142        self._scopes.insert(String::from(scope.as_ref()));
26143        self
26144    }
26145    /// Identifies the authorization scope(s) for the method you are building.
26146    ///
26147    /// See [`Self::add_scope()`] for details.
26148    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserSettingUpdateVacationCall<'a, C>
26149    where
26150        I: IntoIterator<Item = St>,
26151        St: AsRef<str>,
26152    {
26153        self._scopes
26154            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
26155        self
26156    }
26157
26158    /// Removes all scopes, and no default scope will be used either.
26159    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
26160    /// for details).
26161    pub fn clear_scopes(mut self) -> UserSettingUpdateVacationCall<'a, C> {
26162        self._scopes.clear();
26163        self
26164    }
26165}
26166
26167/// Immediately and permanently deletes the specified thread. Any messages that belong to the thread are also deleted. This operation cannot be undone. Prefer `threads.trash` instead.
26168///
26169/// A builder for the *threads.delete* method supported by a *user* resource.
26170/// It is not used directly, but through a [`UserMethods`] instance.
26171///
26172/// # Example
26173///
26174/// Instantiate a resource method builder
26175///
26176/// ```test_harness,no_run
26177/// # extern crate hyper;
26178/// # extern crate hyper_rustls;
26179/// # extern crate google_gmail1 as gmail1;
26180/// # async fn dox() {
26181/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
26182///
26183/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
26184/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
26185/// #     secret,
26186/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
26187/// # ).build().await.unwrap();
26188///
26189/// # let client = hyper_util::client::legacy::Client::builder(
26190/// #     hyper_util::rt::TokioExecutor::new()
26191/// # )
26192/// # .build(
26193/// #     hyper_rustls::HttpsConnectorBuilder::new()
26194/// #         .with_native_roots()
26195/// #         .unwrap()
26196/// #         .https_or_http()
26197/// #         .enable_http1()
26198/// #         .build()
26199/// # );
26200/// # let mut hub = Gmail::new(client, auth);
26201/// // You can configure optional parameters by calling the respective setters at will, and
26202/// // execute the final call using `doit()`.
26203/// // Values shown here are possibly random and not representative !
26204/// let result = hub.users().threads_delete("userId", "id")
26205///              .doit().await;
26206/// # }
26207/// ```
26208pub struct UserThreadDeleteCall<'a, C>
26209where
26210    C: 'a,
26211{
26212    hub: &'a Gmail<C>,
26213    _user_id: String,
26214    _id: String,
26215    _delegate: Option<&'a mut dyn common::Delegate>,
26216    _additional_params: HashMap<String, String>,
26217    _scopes: BTreeSet<String>,
26218}
26219
26220impl<'a, C> common::CallBuilder for UserThreadDeleteCall<'a, C> {}
26221
26222impl<'a, C> UserThreadDeleteCall<'a, C>
26223where
26224    C: common::Connector,
26225{
26226    /// Perform the operation you have build so far.
26227    pub async fn doit(mut self) -> common::Result<common::Response> {
26228        use std::borrow::Cow;
26229        use std::io::{Read, Seek};
26230
26231        use common::{url::Params, ToParts};
26232        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
26233
26234        let mut dd = common::DefaultDelegate;
26235        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
26236        dlg.begin(common::MethodInfo {
26237            id: "gmail.users.threads.delete",
26238            http_method: hyper::Method::DELETE,
26239        });
26240
26241        for &field in ["userId", "id"].iter() {
26242            if self._additional_params.contains_key(field) {
26243                dlg.finished(false);
26244                return Err(common::Error::FieldClash(field));
26245            }
26246        }
26247
26248        let mut params = Params::with_capacity(3 + self._additional_params.len());
26249        params.push("userId", self._user_id);
26250        params.push("id", self._id);
26251
26252        params.extend(self._additional_params.iter());
26253
26254        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/threads/{id}";
26255        if self._scopes.is_empty() {
26256            self._scopes.insert(Scope::Gmai.as_ref().to_string());
26257        }
26258
26259        #[allow(clippy::single_element_loop)]
26260        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
26261            url = params.uri_replacement(url, param_name, find_this, false);
26262        }
26263        {
26264            let to_remove = ["id", "userId"];
26265            params.remove_params(&to_remove);
26266        }
26267
26268        let url = params.parse_with_url(&url);
26269
26270        loop {
26271            let token = match self
26272                .hub
26273                .auth
26274                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
26275                .await
26276            {
26277                Ok(token) => token,
26278                Err(e) => match dlg.token(e) {
26279                    Ok(token) => token,
26280                    Err(e) => {
26281                        dlg.finished(false);
26282                        return Err(common::Error::MissingToken(e));
26283                    }
26284                },
26285            };
26286            let mut req_result = {
26287                let client = &self.hub.client;
26288                dlg.pre_request();
26289                let mut req_builder = hyper::Request::builder()
26290                    .method(hyper::Method::DELETE)
26291                    .uri(url.as_str())
26292                    .header(USER_AGENT, self.hub._user_agent.clone());
26293
26294                if let Some(token) = token.as_ref() {
26295                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
26296                }
26297
26298                let request = req_builder
26299                    .header(CONTENT_LENGTH, 0_u64)
26300                    .body(common::to_body::<String>(None));
26301
26302                client.request(request.unwrap()).await
26303            };
26304
26305            match req_result {
26306                Err(err) => {
26307                    if let common::Retry::After(d) = dlg.http_error(&err) {
26308                        sleep(d).await;
26309                        continue;
26310                    }
26311                    dlg.finished(false);
26312                    return Err(common::Error::HttpError(err));
26313                }
26314                Ok(res) => {
26315                    let (mut parts, body) = res.into_parts();
26316                    let mut body = common::Body::new(body);
26317                    if !parts.status.is_success() {
26318                        let bytes = common::to_bytes(body).await.unwrap_or_default();
26319                        let error = serde_json::from_str(&common::to_string(&bytes));
26320                        let response = common::to_response(parts, bytes.into());
26321
26322                        if let common::Retry::After(d) =
26323                            dlg.http_failure(&response, error.as_ref().ok())
26324                        {
26325                            sleep(d).await;
26326                            continue;
26327                        }
26328
26329                        dlg.finished(false);
26330
26331                        return Err(match error {
26332                            Ok(value) => common::Error::BadRequest(value),
26333                            _ => common::Error::Failure(response),
26334                        });
26335                    }
26336                    let response = common::Response::from_parts(parts, body);
26337
26338                    dlg.finished(true);
26339                    return Ok(response);
26340                }
26341            }
26342        }
26343    }
26344
26345    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
26346    ///
26347    /// Sets the *user id* path property to the given value.
26348    ///
26349    /// Even though the property as already been set when instantiating this call,
26350    /// we provide this method for API completeness.
26351    pub fn user_id(mut self, new_value: &str) -> UserThreadDeleteCall<'a, C> {
26352        self._user_id = new_value.to_string();
26353        self
26354    }
26355    /// ID of the Thread to delete.
26356    ///
26357    /// Sets the *id* path property to the given value.
26358    ///
26359    /// Even though the property as already been set when instantiating this call,
26360    /// we provide this method for API completeness.
26361    pub fn id(mut self, new_value: &str) -> UserThreadDeleteCall<'a, C> {
26362        self._id = new_value.to_string();
26363        self
26364    }
26365    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
26366    /// while executing the actual API request.
26367    ///
26368    /// ````text
26369    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
26370    /// ````
26371    ///
26372    /// Sets the *delegate* property to the given value.
26373    pub fn delegate(
26374        mut self,
26375        new_value: &'a mut dyn common::Delegate,
26376    ) -> UserThreadDeleteCall<'a, C> {
26377        self._delegate = Some(new_value);
26378        self
26379    }
26380
26381    /// Set any additional parameter of the query string used in the request.
26382    /// It should be used to set parameters which are not yet available through their own
26383    /// setters.
26384    ///
26385    /// Please note that this method must not be used to set any of the known parameters
26386    /// which have their own setter method. If done anyway, the request will fail.
26387    ///
26388    /// # Additional Parameters
26389    ///
26390    /// * *$.xgafv* (query-string) - V1 error format.
26391    /// * *access_token* (query-string) - OAuth access token.
26392    /// * *alt* (query-string) - Data format for response.
26393    /// * *callback* (query-string) - JSONP
26394    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
26395    /// * *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.
26396    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
26397    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
26398    /// * *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.
26399    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
26400    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
26401    pub fn param<T>(mut self, name: T, value: T) -> UserThreadDeleteCall<'a, C>
26402    where
26403        T: AsRef<str>,
26404    {
26405        self._additional_params
26406            .insert(name.as_ref().to_string(), value.as_ref().to_string());
26407        self
26408    }
26409
26410    /// Identifies the authorization scope for the method you are building.
26411    ///
26412    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
26413    /// [`Scope::Gmai`].
26414    ///
26415    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
26416    /// tokens for more than one scope.
26417    ///
26418    /// Usually there is more than one suitable scope to authorize an operation, some of which may
26419    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
26420    /// sufficient, a read-write scope will do as well.
26421    pub fn add_scope<St>(mut self, scope: St) -> UserThreadDeleteCall<'a, C>
26422    where
26423        St: AsRef<str>,
26424    {
26425        self._scopes.insert(String::from(scope.as_ref()));
26426        self
26427    }
26428    /// Identifies the authorization scope(s) for the method you are building.
26429    ///
26430    /// See [`Self::add_scope()`] for details.
26431    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserThreadDeleteCall<'a, C>
26432    where
26433        I: IntoIterator<Item = St>,
26434        St: AsRef<str>,
26435    {
26436        self._scopes
26437            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
26438        self
26439    }
26440
26441    /// Removes all scopes, and no default scope will be used either.
26442    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
26443    /// for details).
26444    pub fn clear_scopes(mut self) -> UserThreadDeleteCall<'a, C> {
26445        self._scopes.clear();
26446        self
26447    }
26448}
26449
26450/// Gets the specified thread.
26451///
26452/// A builder for the *threads.get* method supported by a *user* resource.
26453/// It is not used directly, but through a [`UserMethods`] instance.
26454///
26455/// # Example
26456///
26457/// Instantiate a resource method builder
26458///
26459/// ```test_harness,no_run
26460/// # extern crate hyper;
26461/// # extern crate hyper_rustls;
26462/// # extern crate google_gmail1 as gmail1;
26463/// # async fn dox() {
26464/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
26465///
26466/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
26467/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
26468/// #     secret,
26469/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
26470/// # ).build().await.unwrap();
26471///
26472/// # let client = hyper_util::client::legacy::Client::builder(
26473/// #     hyper_util::rt::TokioExecutor::new()
26474/// # )
26475/// # .build(
26476/// #     hyper_rustls::HttpsConnectorBuilder::new()
26477/// #         .with_native_roots()
26478/// #         .unwrap()
26479/// #         .https_or_http()
26480/// #         .enable_http1()
26481/// #         .build()
26482/// # );
26483/// # let mut hub = Gmail::new(client, auth);
26484/// // You can configure optional parameters by calling the respective setters at will, and
26485/// // execute the final call using `doit()`.
26486/// // Values shown here are possibly random and not representative !
26487/// let result = hub.users().threads_get("userId", "id")
26488///              .add_metadata_headers("takimata")
26489///              .format("Lorem")
26490///              .doit().await;
26491/// # }
26492/// ```
26493pub struct UserThreadGetCall<'a, C>
26494where
26495    C: 'a,
26496{
26497    hub: &'a Gmail<C>,
26498    _user_id: String,
26499    _id: String,
26500    _metadata_headers: Vec<String>,
26501    _format: Option<String>,
26502    _delegate: Option<&'a mut dyn common::Delegate>,
26503    _additional_params: HashMap<String, String>,
26504    _scopes: BTreeSet<String>,
26505}
26506
26507impl<'a, C> common::CallBuilder for UserThreadGetCall<'a, C> {}
26508
26509impl<'a, C> UserThreadGetCall<'a, C>
26510where
26511    C: common::Connector,
26512{
26513    /// Perform the operation you have build so far.
26514    pub async fn doit(mut self) -> common::Result<(common::Response, Thread)> {
26515        use std::borrow::Cow;
26516        use std::io::{Read, Seek};
26517
26518        use common::{url::Params, ToParts};
26519        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
26520
26521        let mut dd = common::DefaultDelegate;
26522        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
26523        dlg.begin(common::MethodInfo {
26524            id: "gmail.users.threads.get",
26525            http_method: hyper::Method::GET,
26526        });
26527
26528        for &field in ["alt", "userId", "id", "metadataHeaders", "format"].iter() {
26529            if self._additional_params.contains_key(field) {
26530                dlg.finished(false);
26531                return Err(common::Error::FieldClash(field));
26532            }
26533        }
26534
26535        let mut params = Params::with_capacity(6 + self._additional_params.len());
26536        params.push("userId", self._user_id);
26537        params.push("id", self._id);
26538        if !self._metadata_headers.is_empty() {
26539            for f in self._metadata_headers.iter() {
26540                params.push("metadataHeaders", f);
26541            }
26542        }
26543        if let Some(value) = self._format.as_ref() {
26544            params.push("format", value);
26545        }
26546
26547        params.extend(self._additional_params.iter());
26548
26549        params.push("alt", "json");
26550        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/threads/{id}";
26551        if self._scopes.is_empty() {
26552            self._scopes
26553                .insert(Scope::AddonCurrentMessageReadonly.as_ref().to_string());
26554        }
26555
26556        #[allow(clippy::single_element_loop)]
26557        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
26558            url = params.uri_replacement(url, param_name, find_this, false);
26559        }
26560        {
26561            let to_remove = ["id", "userId"];
26562            params.remove_params(&to_remove);
26563        }
26564
26565        let url = params.parse_with_url(&url);
26566
26567        loop {
26568            let token = match self
26569                .hub
26570                .auth
26571                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
26572                .await
26573            {
26574                Ok(token) => token,
26575                Err(e) => match dlg.token(e) {
26576                    Ok(token) => token,
26577                    Err(e) => {
26578                        dlg.finished(false);
26579                        return Err(common::Error::MissingToken(e));
26580                    }
26581                },
26582            };
26583            let mut req_result = {
26584                let client = &self.hub.client;
26585                dlg.pre_request();
26586                let mut req_builder = hyper::Request::builder()
26587                    .method(hyper::Method::GET)
26588                    .uri(url.as_str())
26589                    .header(USER_AGENT, self.hub._user_agent.clone());
26590
26591                if let Some(token) = token.as_ref() {
26592                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
26593                }
26594
26595                let request = req_builder
26596                    .header(CONTENT_LENGTH, 0_u64)
26597                    .body(common::to_body::<String>(None));
26598
26599                client.request(request.unwrap()).await
26600            };
26601
26602            match req_result {
26603                Err(err) => {
26604                    if let common::Retry::After(d) = dlg.http_error(&err) {
26605                        sleep(d).await;
26606                        continue;
26607                    }
26608                    dlg.finished(false);
26609                    return Err(common::Error::HttpError(err));
26610                }
26611                Ok(res) => {
26612                    let (mut parts, body) = res.into_parts();
26613                    let mut body = common::Body::new(body);
26614                    if !parts.status.is_success() {
26615                        let bytes = common::to_bytes(body).await.unwrap_or_default();
26616                        let error = serde_json::from_str(&common::to_string(&bytes));
26617                        let response = common::to_response(parts, bytes.into());
26618
26619                        if let common::Retry::After(d) =
26620                            dlg.http_failure(&response, error.as_ref().ok())
26621                        {
26622                            sleep(d).await;
26623                            continue;
26624                        }
26625
26626                        dlg.finished(false);
26627
26628                        return Err(match error {
26629                            Ok(value) => common::Error::BadRequest(value),
26630                            _ => common::Error::Failure(response),
26631                        });
26632                    }
26633                    let response = {
26634                        let bytes = common::to_bytes(body).await.unwrap_or_default();
26635                        let encoded = common::to_string(&bytes);
26636                        match serde_json::from_str(&encoded) {
26637                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
26638                            Err(error) => {
26639                                dlg.response_json_decode_error(&encoded, &error);
26640                                return Err(common::Error::JsonDecodeError(
26641                                    encoded.to_string(),
26642                                    error,
26643                                ));
26644                            }
26645                        }
26646                    };
26647
26648                    dlg.finished(true);
26649                    return Ok(response);
26650                }
26651            }
26652        }
26653    }
26654
26655    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
26656    ///
26657    /// Sets the *user id* path property to the given value.
26658    ///
26659    /// Even though the property as already been set when instantiating this call,
26660    /// we provide this method for API completeness.
26661    pub fn user_id(mut self, new_value: &str) -> UserThreadGetCall<'a, C> {
26662        self._user_id = new_value.to_string();
26663        self
26664    }
26665    /// The ID of the thread to retrieve.
26666    ///
26667    /// Sets the *id* path property to the given value.
26668    ///
26669    /// Even though the property as already been set when instantiating this call,
26670    /// we provide this method for API completeness.
26671    pub fn id(mut self, new_value: &str) -> UserThreadGetCall<'a, C> {
26672        self._id = new_value.to_string();
26673        self
26674    }
26675    /// When given and format is METADATA, only include headers specified.
26676    ///
26677    /// Append the given value to the *metadata headers* query property.
26678    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
26679    pub fn add_metadata_headers(mut self, new_value: &str) -> UserThreadGetCall<'a, C> {
26680        self._metadata_headers.push(new_value.to_string());
26681        self
26682    }
26683    /// The format to return the messages in.
26684    ///
26685    /// Sets the *format* query property to the given value.
26686    pub fn format(mut self, new_value: &str) -> UserThreadGetCall<'a, C> {
26687        self._format = Some(new_value.to_string());
26688        self
26689    }
26690    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
26691    /// while executing the actual API request.
26692    ///
26693    /// ````text
26694    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
26695    /// ````
26696    ///
26697    /// Sets the *delegate* property to the given value.
26698    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> UserThreadGetCall<'a, C> {
26699        self._delegate = Some(new_value);
26700        self
26701    }
26702
26703    /// Set any additional parameter of the query string used in the request.
26704    /// It should be used to set parameters which are not yet available through their own
26705    /// setters.
26706    ///
26707    /// Please note that this method must not be used to set any of the known parameters
26708    /// which have their own setter method. If done anyway, the request will fail.
26709    ///
26710    /// # Additional Parameters
26711    ///
26712    /// * *$.xgafv* (query-string) - V1 error format.
26713    /// * *access_token* (query-string) - OAuth access token.
26714    /// * *alt* (query-string) - Data format for response.
26715    /// * *callback* (query-string) - JSONP
26716    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
26717    /// * *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.
26718    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
26719    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
26720    /// * *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.
26721    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
26722    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
26723    pub fn param<T>(mut self, name: T, value: T) -> UserThreadGetCall<'a, C>
26724    where
26725        T: AsRef<str>,
26726    {
26727        self._additional_params
26728            .insert(name.as_ref().to_string(), value.as_ref().to_string());
26729        self
26730    }
26731
26732    /// Identifies the authorization scope for the method you are building.
26733    ///
26734    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
26735    /// [`Scope::AddonCurrentMessageReadonly`].
26736    ///
26737    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
26738    /// tokens for more than one scope.
26739    ///
26740    /// Usually there is more than one suitable scope to authorize an operation, some of which may
26741    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
26742    /// sufficient, a read-write scope will do as well.
26743    pub fn add_scope<St>(mut self, scope: St) -> UserThreadGetCall<'a, C>
26744    where
26745        St: AsRef<str>,
26746    {
26747        self._scopes.insert(String::from(scope.as_ref()));
26748        self
26749    }
26750    /// Identifies the authorization scope(s) for the method you are building.
26751    ///
26752    /// See [`Self::add_scope()`] for details.
26753    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserThreadGetCall<'a, C>
26754    where
26755        I: IntoIterator<Item = St>,
26756        St: AsRef<str>,
26757    {
26758        self._scopes
26759            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
26760        self
26761    }
26762
26763    /// Removes all scopes, and no default scope will be used either.
26764    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
26765    /// for details).
26766    pub fn clear_scopes(mut self) -> UserThreadGetCall<'a, C> {
26767        self._scopes.clear();
26768        self
26769    }
26770}
26771
26772/// Lists the threads in the user's mailbox.
26773///
26774/// A builder for the *threads.list* method supported by a *user* resource.
26775/// It is not used directly, but through a [`UserMethods`] instance.
26776///
26777/// # Example
26778///
26779/// Instantiate a resource method builder
26780///
26781/// ```test_harness,no_run
26782/// # extern crate hyper;
26783/// # extern crate hyper_rustls;
26784/// # extern crate google_gmail1 as gmail1;
26785/// # async fn dox() {
26786/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
26787///
26788/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
26789/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
26790/// #     secret,
26791/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
26792/// # ).build().await.unwrap();
26793///
26794/// # let client = hyper_util::client::legacy::Client::builder(
26795/// #     hyper_util::rt::TokioExecutor::new()
26796/// # )
26797/// # .build(
26798/// #     hyper_rustls::HttpsConnectorBuilder::new()
26799/// #         .with_native_roots()
26800/// #         .unwrap()
26801/// #         .https_or_http()
26802/// #         .enable_http1()
26803/// #         .build()
26804/// # );
26805/// # let mut hub = Gmail::new(client, auth);
26806/// // You can configure optional parameters by calling the respective setters at will, and
26807/// // execute the final call using `doit()`.
26808/// // Values shown here are possibly random and not representative !
26809/// let result = hub.users().threads_list("userId")
26810///              .q("At")
26811///              .page_token("dolor")
26812///              .max_results(79)
26813///              .add_label_ids("sit")
26814///              .include_spam_trash(false)
26815///              .doit().await;
26816/// # }
26817/// ```
26818pub struct UserThreadListCall<'a, C>
26819where
26820    C: 'a,
26821{
26822    hub: &'a Gmail<C>,
26823    _user_id: String,
26824    _q: Option<String>,
26825    _page_token: Option<String>,
26826    _max_results: Option<u32>,
26827    _label_ids: Vec<String>,
26828    _include_spam_trash: Option<bool>,
26829    _delegate: Option<&'a mut dyn common::Delegate>,
26830    _additional_params: HashMap<String, String>,
26831    _scopes: BTreeSet<String>,
26832}
26833
26834impl<'a, C> common::CallBuilder for UserThreadListCall<'a, C> {}
26835
26836impl<'a, C> UserThreadListCall<'a, C>
26837where
26838    C: common::Connector,
26839{
26840    /// Perform the operation you have build so far.
26841    pub async fn doit(mut self) -> common::Result<(common::Response, ListThreadsResponse)> {
26842        use std::borrow::Cow;
26843        use std::io::{Read, Seek};
26844
26845        use common::{url::Params, ToParts};
26846        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
26847
26848        let mut dd = common::DefaultDelegate;
26849        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
26850        dlg.begin(common::MethodInfo {
26851            id: "gmail.users.threads.list",
26852            http_method: hyper::Method::GET,
26853        });
26854
26855        for &field in [
26856            "alt",
26857            "userId",
26858            "q",
26859            "pageToken",
26860            "maxResults",
26861            "labelIds",
26862            "includeSpamTrash",
26863        ]
26864        .iter()
26865        {
26866            if self._additional_params.contains_key(field) {
26867                dlg.finished(false);
26868                return Err(common::Error::FieldClash(field));
26869            }
26870        }
26871
26872        let mut params = Params::with_capacity(8 + self._additional_params.len());
26873        params.push("userId", self._user_id);
26874        if let Some(value) = self._q.as_ref() {
26875            params.push("q", value);
26876        }
26877        if let Some(value) = self._page_token.as_ref() {
26878            params.push("pageToken", value);
26879        }
26880        if let Some(value) = self._max_results.as_ref() {
26881            params.push("maxResults", value.to_string());
26882        }
26883        if !self._label_ids.is_empty() {
26884            for f in self._label_ids.iter() {
26885                params.push("labelIds", f);
26886            }
26887        }
26888        if let Some(value) = self._include_spam_trash.as_ref() {
26889            params.push("includeSpamTrash", value.to_string());
26890        }
26891
26892        params.extend(self._additional_params.iter());
26893
26894        params.push("alt", "json");
26895        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/threads";
26896        if self._scopes.is_empty() {
26897            self._scopes.insert(Scope::Readonly.as_ref().to_string());
26898        }
26899
26900        #[allow(clippy::single_element_loop)]
26901        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
26902            url = params.uri_replacement(url, param_name, find_this, false);
26903        }
26904        {
26905            let to_remove = ["userId"];
26906            params.remove_params(&to_remove);
26907        }
26908
26909        let url = params.parse_with_url(&url);
26910
26911        loop {
26912            let token = match self
26913                .hub
26914                .auth
26915                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
26916                .await
26917            {
26918                Ok(token) => token,
26919                Err(e) => match dlg.token(e) {
26920                    Ok(token) => token,
26921                    Err(e) => {
26922                        dlg.finished(false);
26923                        return Err(common::Error::MissingToken(e));
26924                    }
26925                },
26926            };
26927            let mut req_result = {
26928                let client = &self.hub.client;
26929                dlg.pre_request();
26930                let mut req_builder = hyper::Request::builder()
26931                    .method(hyper::Method::GET)
26932                    .uri(url.as_str())
26933                    .header(USER_AGENT, self.hub._user_agent.clone());
26934
26935                if let Some(token) = token.as_ref() {
26936                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
26937                }
26938
26939                let request = req_builder
26940                    .header(CONTENT_LENGTH, 0_u64)
26941                    .body(common::to_body::<String>(None));
26942
26943                client.request(request.unwrap()).await
26944            };
26945
26946            match req_result {
26947                Err(err) => {
26948                    if let common::Retry::After(d) = dlg.http_error(&err) {
26949                        sleep(d).await;
26950                        continue;
26951                    }
26952                    dlg.finished(false);
26953                    return Err(common::Error::HttpError(err));
26954                }
26955                Ok(res) => {
26956                    let (mut parts, body) = res.into_parts();
26957                    let mut body = common::Body::new(body);
26958                    if !parts.status.is_success() {
26959                        let bytes = common::to_bytes(body).await.unwrap_or_default();
26960                        let error = serde_json::from_str(&common::to_string(&bytes));
26961                        let response = common::to_response(parts, bytes.into());
26962
26963                        if let common::Retry::After(d) =
26964                            dlg.http_failure(&response, error.as_ref().ok())
26965                        {
26966                            sleep(d).await;
26967                            continue;
26968                        }
26969
26970                        dlg.finished(false);
26971
26972                        return Err(match error {
26973                            Ok(value) => common::Error::BadRequest(value),
26974                            _ => common::Error::Failure(response),
26975                        });
26976                    }
26977                    let response = {
26978                        let bytes = common::to_bytes(body).await.unwrap_or_default();
26979                        let encoded = common::to_string(&bytes);
26980                        match serde_json::from_str(&encoded) {
26981                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
26982                            Err(error) => {
26983                                dlg.response_json_decode_error(&encoded, &error);
26984                                return Err(common::Error::JsonDecodeError(
26985                                    encoded.to_string(),
26986                                    error,
26987                                ));
26988                            }
26989                        }
26990                    };
26991
26992                    dlg.finished(true);
26993                    return Ok(response);
26994                }
26995            }
26996        }
26997    }
26998
26999    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
27000    ///
27001    /// Sets the *user id* path property to the given value.
27002    ///
27003    /// Even though the property as already been set when instantiating this call,
27004    /// we provide this method for API completeness.
27005    pub fn user_id(mut self, new_value: &str) -> UserThreadListCall<'a, C> {
27006        self._user_id = new_value.to_string();
27007        self
27008    }
27009    /// Only return threads matching the specified query. Supports the same query format as the Gmail search box. For example, `"from:someuser@example.com rfc822msgid: is:unread"`. Parameter cannot be used when accessing the api using the gmail.metadata scope.
27010    ///
27011    /// Sets the *q* query property to the given value.
27012    pub fn q(mut self, new_value: &str) -> UserThreadListCall<'a, C> {
27013        self._q = Some(new_value.to_string());
27014        self
27015    }
27016    /// Page token to retrieve a specific page of results in the list.
27017    ///
27018    /// Sets the *page token* query property to the given value.
27019    pub fn page_token(mut self, new_value: &str) -> UserThreadListCall<'a, C> {
27020        self._page_token = Some(new_value.to_string());
27021        self
27022    }
27023    /// Maximum number of threads to return. This field defaults to 100. The maximum allowed value for this field is 500.
27024    ///
27025    /// Sets the *max results* query property to the given value.
27026    pub fn max_results(mut self, new_value: u32) -> UserThreadListCall<'a, C> {
27027        self._max_results = Some(new_value);
27028        self
27029    }
27030    /// Only return threads with labels that match all of the specified label IDs.
27031    ///
27032    /// Append the given value to the *label ids* query property.
27033    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
27034    pub fn add_label_ids(mut self, new_value: &str) -> UserThreadListCall<'a, C> {
27035        self._label_ids.push(new_value.to_string());
27036        self
27037    }
27038    /// Include threads from `SPAM` and `TRASH` in the results.
27039    ///
27040    /// Sets the *include spam trash* query property to the given value.
27041    pub fn include_spam_trash(mut self, new_value: bool) -> UserThreadListCall<'a, C> {
27042        self._include_spam_trash = Some(new_value);
27043        self
27044    }
27045    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
27046    /// while executing the actual API request.
27047    ///
27048    /// ````text
27049    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
27050    /// ````
27051    ///
27052    /// Sets the *delegate* property to the given value.
27053    pub fn delegate(
27054        mut self,
27055        new_value: &'a mut dyn common::Delegate,
27056    ) -> UserThreadListCall<'a, C> {
27057        self._delegate = Some(new_value);
27058        self
27059    }
27060
27061    /// Set any additional parameter of the query string used in the request.
27062    /// It should be used to set parameters which are not yet available through their own
27063    /// setters.
27064    ///
27065    /// Please note that this method must not be used to set any of the known parameters
27066    /// which have their own setter method. If done anyway, the request will fail.
27067    ///
27068    /// # Additional Parameters
27069    ///
27070    /// * *$.xgafv* (query-string) - V1 error format.
27071    /// * *access_token* (query-string) - OAuth access token.
27072    /// * *alt* (query-string) - Data format for response.
27073    /// * *callback* (query-string) - JSONP
27074    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
27075    /// * *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.
27076    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
27077    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
27078    /// * *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.
27079    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
27080    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
27081    pub fn param<T>(mut self, name: T, value: T) -> UserThreadListCall<'a, C>
27082    where
27083        T: AsRef<str>,
27084    {
27085        self._additional_params
27086            .insert(name.as_ref().to_string(), value.as_ref().to_string());
27087        self
27088    }
27089
27090    /// Identifies the authorization scope for the method you are building.
27091    ///
27092    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
27093    /// [`Scope::Readonly`].
27094    ///
27095    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
27096    /// tokens for more than one scope.
27097    ///
27098    /// Usually there is more than one suitable scope to authorize an operation, some of which may
27099    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
27100    /// sufficient, a read-write scope will do as well.
27101    pub fn add_scope<St>(mut self, scope: St) -> UserThreadListCall<'a, C>
27102    where
27103        St: AsRef<str>,
27104    {
27105        self._scopes.insert(String::from(scope.as_ref()));
27106        self
27107    }
27108    /// Identifies the authorization scope(s) for the method you are building.
27109    ///
27110    /// See [`Self::add_scope()`] for details.
27111    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserThreadListCall<'a, C>
27112    where
27113        I: IntoIterator<Item = St>,
27114        St: AsRef<str>,
27115    {
27116        self._scopes
27117            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
27118        self
27119    }
27120
27121    /// Removes all scopes, and no default scope will be used either.
27122    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
27123    /// for details).
27124    pub fn clear_scopes(mut self) -> UserThreadListCall<'a, C> {
27125        self._scopes.clear();
27126        self
27127    }
27128}
27129
27130/// Modifies the labels applied to the thread. This applies to all messages in the thread.
27131///
27132/// A builder for the *threads.modify* method supported by a *user* resource.
27133/// It is not used directly, but through a [`UserMethods`] instance.
27134///
27135/// # Example
27136///
27137/// Instantiate a resource method builder
27138///
27139/// ```test_harness,no_run
27140/// # extern crate hyper;
27141/// # extern crate hyper_rustls;
27142/// # extern crate google_gmail1 as gmail1;
27143/// use gmail1::api::ModifyThreadRequest;
27144/// # async fn dox() {
27145/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
27146///
27147/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
27148/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
27149/// #     secret,
27150/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
27151/// # ).build().await.unwrap();
27152///
27153/// # let client = hyper_util::client::legacy::Client::builder(
27154/// #     hyper_util::rt::TokioExecutor::new()
27155/// # )
27156/// # .build(
27157/// #     hyper_rustls::HttpsConnectorBuilder::new()
27158/// #         .with_native_roots()
27159/// #         .unwrap()
27160/// #         .https_or_http()
27161/// #         .enable_http1()
27162/// #         .build()
27163/// # );
27164/// # let mut hub = Gmail::new(client, auth);
27165/// // As the method needs a request, you would usually fill it with the desired information
27166/// // into the respective structure. Some of the parts shown here might not be applicable !
27167/// // Values shown here are possibly random and not representative !
27168/// let mut req = ModifyThreadRequest::default();
27169///
27170/// // You can configure optional parameters by calling the respective setters at will, and
27171/// // execute the final call using `doit()`.
27172/// // Values shown here are possibly random and not representative !
27173/// let result = hub.users().threads_modify(req, "userId", "id")
27174///              .doit().await;
27175/// # }
27176/// ```
27177pub struct UserThreadModifyCall<'a, C>
27178where
27179    C: 'a,
27180{
27181    hub: &'a Gmail<C>,
27182    _request: ModifyThreadRequest,
27183    _user_id: String,
27184    _id: String,
27185    _delegate: Option<&'a mut dyn common::Delegate>,
27186    _additional_params: HashMap<String, String>,
27187    _scopes: BTreeSet<String>,
27188}
27189
27190impl<'a, C> common::CallBuilder for UserThreadModifyCall<'a, C> {}
27191
27192impl<'a, C> UserThreadModifyCall<'a, C>
27193where
27194    C: common::Connector,
27195{
27196    /// Perform the operation you have build so far.
27197    pub async fn doit(mut self) -> common::Result<(common::Response, Thread)> {
27198        use std::borrow::Cow;
27199        use std::io::{Read, Seek};
27200
27201        use common::{url::Params, ToParts};
27202        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
27203
27204        let mut dd = common::DefaultDelegate;
27205        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
27206        dlg.begin(common::MethodInfo {
27207            id: "gmail.users.threads.modify",
27208            http_method: hyper::Method::POST,
27209        });
27210
27211        for &field in ["alt", "userId", "id"].iter() {
27212            if self._additional_params.contains_key(field) {
27213                dlg.finished(false);
27214                return Err(common::Error::FieldClash(field));
27215            }
27216        }
27217
27218        let mut params = Params::with_capacity(5 + self._additional_params.len());
27219        params.push("userId", self._user_id);
27220        params.push("id", self._id);
27221
27222        params.extend(self._additional_params.iter());
27223
27224        params.push("alt", "json");
27225        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/threads/{id}/modify";
27226        if self._scopes.is_empty() {
27227            self._scopes.insert(Scope::Gmai.as_ref().to_string());
27228        }
27229
27230        #[allow(clippy::single_element_loop)]
27231        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
27232            url = params.uri_replacement(url, param_name, find_this, false);
27233        }
27234        {
27235            let to_remove = ["id", "userId"];
27236            params.remove_params(&to_remove);
27237        }
27238
27239        let url = params.parse_with_url(&url);
27240
27241        let mut json_mime_type = mime::APPLICATION_JSON;
27242        let mut request_value_reader = {
27243            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
27244            common::remove_json_null_values(&mut value);
27245            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
27246            serde_json::to_writer(&mut dst, &value).unwrap();
27247            dst
27248        };
27249        let request_size = request_value_reader
27250            .seek(std::io::SeekFrom::End(0))
27251            .unwrap();
27252        request_value_reader
27253            .seek(std::io::SeekFrom::Start(0))
27254            .unwrap();
27255
27256        loop {
27257            let token = match self
27258                .hub
27259                .auth
27260                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
27261                .await
27262            {
27263                Ok(token) => token,
27264                Err(e) => match dlg.token(e) {
27265                    Ok(token) => token,
27266                    Err(e) => {
27267                        dlg.finished(false);
27268                        return Err(common::Error::MissingToken(e));
27269                    }
27270                },
27271            };
27272            request_value_reader
27273                .seek(std::io::SeekFrom::Start(0))
27274                .unwrap();
27275            let mut req_result = {
27276                let client = &self.hub.client;
27277                dlg.pre_request();
27278                let mut req_builder = hyper::Request::builder()
27279                    .method(hyper::Method::POST)
27280                    .uri(url.as_str())
27281                    .header(USER_AGENT, self.hub._user_agent.clone());
27282
27283                if let Some(token) = token.as_ref() {
27284                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
27285                }
27286
27287                let request = req_builder
27288                    .header(CONTENT_TYPE, json_mime_type.to_string())
27289                    .header(CONTENT_LENGTH, request_size as u64)
27290                    .body(common::to_body(
27291                        request_value_reader.get_ref().clone().into(),
27292                    ));
27293
27294                client.request(request.unwrap()).await
27295            };
27296
27297            match req_result {
27298                Err(err) => {
27299                    if let common::Retry::After(d) = dlg.http_error(&err) {
27300                        sleep(d).await;
27301                        continue;
27302                    }
27303                    dlg.finished(false);
27304                    return Err(common::Error::HttpError(err));
27305                }
27306                Ok(res) => {
27307                    let (mut parts, body) = res.into_parts();
27308                    let mut body = common::Body::new(body);
27309                    if !parts.status.is_success() {
27310                        let bytes = common::to_bytes(body).await.unwrap_or_default();
27311                        let error = serde_json::from_str(&common::to_string(&bytes));
27312                        let response = common::to_response(parts, bytes.into());
27313
27314                        if let common::Retry::After(d) =
27315                            dlg.http_failure(&response, error.as_ref().ok())
27316                        {
27317                            sleep(d).await;
27318                            continue;
27319                        }
27320
27321                        dlg.finished(false);
27322
27323                        return Err(match error {
27324                            Ok(value) => common::Error::BadRequest(value),
27325                            _ => common::Error::Failure(response),
27326                        });
27327                    }
27328                    let response = {
27329                        let bytes = common::to_bytes(body).await.unwrap_or_default();
27330                        let encoded = common::to_string(&bytes);
27331                        match serde_json::from_str(&encoded) {
27332                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
27333                            Err(error) => {
27334                                dlg.response_json_decode_error(&encoded, &error);
27335                                return Err(common::Error::JsonDecodeError(
27336                                    encoded.to_string(),
27337                                    error,
27338                                ));
27339                            }
27340                        }
27341                    };
27342
27343                    dlg.finished(true);
27344                    return Ok(response);
27345                }
27346            }
27347        }
27348    }
27349
27350    ///
27351    /// Sets the *request* property to the given value.
27352    ///
27353    /// Even though the property as already been set when instantiating this call,
27354    /// we provide this method for API completeness.
27355    pub fn request(mut self, new_value: ModifyThreadRequest) -> UserThreadModifyCall<'a, C> {
27356        self._request = new_value;
27357        self
27358    }
27359    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
27360    ///
27361    /// Sets the *user id* path property to the given value.
27362    ///
27363    /// Even though the property as already been set when instantiating this call,
27364    /// we provide this method for API completeness.
27365    pub fn user_id(mut self, new_value: &str) -> UserThreadModifyCall<'a, C> {
27366        self._user_id = new_value.to_string();
27367        self
27368    }
27369    /// The ID of the thread to modify.
27370    ///
27371    /// Sets the *id* path property to the given value.
27372    ///
27373    /// Even though the property as already been set when instantiating this call,
27374    /// we provide this method for API completeness.
27375    pub fn id(mut self, new_value: &str) -> UserThreadModifyCall<'a, C> {
27376        self._id = new_value.to_string();
27377        self
27378    }
27379    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
27380    /// while executing the actual API request.
27381    ///
27382    /// ````text
27383    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
27384    /// ````
27385    ///
27386    /// Sets the *delegate* property to the given value.
27387    pub fn delegate(
27388        mut self,
27389        new_value: &'a mut dyn common::Delegate,
27390    ) -> UserThreadModifyCall<'a, C> {
27391        self._delegate = Some(new_value);
27392        self
27393    }
27394
27395    /// Set any additional parameter of the query string used in the request.
27396    /// It should be used to set parameters which are not yet available through their own
27397    /// setters.
27398    ///
27399    /// Please note that this method must not be used to set any of the known parameters
27400    /// which have their own setter method. If done anyway, the request will fail.
27401    ///
27402    /// # Additional Parameters
27403    ///
27404    /// * *$.xgafv* (query-string) - V1 error format.
27405    /// * *access_token* (query-string) - OAuth access token.
27406    /// * *alt* (query-string) - Data format for response.
27407    /// * *callback* (query-string) - JSONP
27408    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
27409    /// * *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.
27410    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
27411    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
27412    /// * *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.
27413    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
27414    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
27415    pub fn param<T>(mut self, name: T, value: T) -> UserThreadModifyCall<'a, C>
27416    where
27417        T: AsRef<str>,
27418    {
27419        self._additional_params
27420            .insert(name.as_ref().to_string(), value.as_ref().to_string());
27421        self
27422    }
27423
27424    /// Identifies the authorization scope for the method you are building.
27425    ///
27426    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
27427    /// [`Scope::Gmai`].
27428    ///
27429    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
27430    /// tokens for more than one scope.
27431    ///
27432    /// Usually there is more than one suitable scope to authorize an operation, some of which may
27433    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
27434    /// sufficient, a read-write scope will do as well.
27435    pub fn add_scope<St>(mut self, scope: St) -> UserThreadModifyCall<'a, C>
27436    where
27437        St: AsRef<str>,
27438    {
27439        self._scopes.insert(String::from(scope.as_ref()));
27440        self
27441    }
27442    /// Identifies the authorization scope(s) for the method you are building.
27443    ///
27444    /// See [`Self::add_scope()`] for details.
27445    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserThreadModifyCall<'a, C>
27446    where
27447        I: IntoIterator<Item = St>,
27448        St: AsRef<str>,
27449    {
27450        self._scopes
27451            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
27452        self
27453    }
27454
27455    /// Removes all scopes, and no default scope will be used either.
27456    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
27457    /// for details).
27458    pub fn clear_scopes(mut self) -> UserThreadModifyCall<'a, C> {
27459        self._scopes.clear();
27460        self
27461    }
27462}
27463
27464/// Moves the specified thread to the trash. Any messages that belong to the thread are also moved to the trash.
27465///
27466/// A builder for the *threads.trash* method supported by a *user* resource.
27467/// It is not used directly, but through a [`UserMethods`] instance.
27468///
27469/// # Example
27470///
27471/// Instantiate a resource method builder
27472///
27473/// ```test_harness,no_run
27474/// # extern crate hyper;
27475/// # extern crate hyper_rustls;
27476/// # extern crate google_gmail1 as gmail1;
27477/// # async fn dox() {
27478/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
27479///
27480/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
27481/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
27482/// #     secret,
27483/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
27484/// # ).build().await.unwrap();
27485///
27486/// # let client = hyper_util::client::legacy::Client::builder(
27487/// #     hyper_util::rt::TokioExecutor::new()
27488/// # )
27489/// # .build(
27490/// #     hyper_rustls::HttpsConnectorBuilder::new()
27491/// #         .with_native_roots()
27492/// #         .unwrap()
27493/// #         .https_or_http()
27494/// #         .enable_http1()
27495/// #         .build()
27496/// # );
27497/// # let mut hub = Gmail::new(client, auth);
27498/// // You can configure optional parameters by calling the respective setters at will, and
27499/// // execute the final call using `doit()`.
27500/// // Values shown here are possibly random and not representative !
27501/// let result = hub.users().threads_trash("userId", "id")
27502///              .doit().await;
27503/// # }
27504/// ```
27505pub struct UserThreadTrashCall<'a, C>
27506where
27507    C: 'a,
27508{
27509    hub: &'a Gmail<C>,
27510    _user_id: String,
27511    _id: String,
27512    _delegate: Option<&'a mut dyn common::Delegate>,
27513    _additional_params: HashMap<String, String>,
27514    _scopes: BTreeSet<String>,
27515}
27516
27517impl<'a, C> common::CallBuilder for UserThreadTrashCall<'a, C> {}
27518
27519impl<'a, C> UserThreadTrashCall<'a, C>
27520where
27521    C: common::Connector,
27522{
27523    /// Perform the operation you have build so far.
27524    pub async fn doit(mut self) -> common::Result<(common::Response, Thread)> {
27525        use std::borrow::Cow;
27526        use std::io::{Read, Seek};
27527
27528        use common::{url::Params, ToParts};
27529        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
27530
27531        let mut dd = common::DefaultDelegate;
27532        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
27533        dlg.begin(common::MethodInfo {
27534            id: "gmail.users.threads.trash",
27535            http_method: hyper::Method::POST,
27536        });
27537
27538        for &field in ["alt", "userId", "id"].iter() {
27539            if self._additional_params.contains_key(field) {
27540                dlg.finished(false);
27541                return Err(common::Error::FieldClash(field));
27542            }
27543        }
27544
27545        let mut params = Params::with_capacity(4 + self._additional_params.len());
27546        params.push("userId", self._user_id);
27547        params.push("id", self._id);
27548
27549        params.extend(self._additional_params.iter());
27550
27551        params.push("alt", "json");
27552        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/threads/{id}/trash";
27553        if self._scopes.is_empty() {
27554            self._scopes.insert(Scope::Gmai.as_ref().to_string());
27555        }
27556
27557        #[allow(clippy::single_element_loop)]
27558        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
27559            url = params.uri_replacement(url, param_name, find_this, false);
27560        }
27561        {
27562            let to_remove = ["id", "userId"];
27563            params.remove_params(&to_remove);
27564        }
27565
27566        let url = params.parse_with_url(&url);
27567
27568        loop {
27569            let token = match self
27570                .hub
27571                .auth
27572                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
27573                .await
27574            {
27575                Ok(token) => token,
27576                Err(e) => match dlg.token(e) {
27577                    Ok(token) => token,
27578                    Err(e) => {
27579                        dlg.finished(false);
27580                        return Err(common::Error::MissingToken(e));
27581                    }
27582                },
27583            };
27584            let mut req_result = {
27585                let client = &self.hub.client;
27586                dlg.pre_request();
27587                let mut req_builder = hyper::Request::builder()
27588                    .method(hyper::Method::POST)
27589                    .uri(url.as_str())
27590                    .header(USER_AGENT, self.hub._user_agent.clone());
27591
27592                if let Some(token) = token.as_ref() {
27593                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
27594                }
27595
27596                let request = req_builder
27597                    .header(CONTENT_LENGTH, 0_u64)
27598                    .body(common::to_body::<String>(None));
27599
27600                client.request(request.unwrap()).await
27601            };
27602
27603            match req_result {
27604                Err(err) => {
27605                    if let common::Retry::After(d) = dlg.http_error(&err) {
27606                        sleep(d).await;
27607                        continue;
27608                    }
27609                    dlg.finished(false);
27610                    return Err(common::Error::HttpError(err));
27611                }
27612                Ok(res) => {
27613                    let (mut parts, body) = res.into_parts();
27614                    let mut body = common::Body::new(body);
27615                    if !parts.status.is_success() {
27616                        let bytes = common::to_bytes(body).await.unwrap_or_default();
27617                        let error = serde_json::from_str(&common::to_string(&bytes));
27618                        let response = common::to_response(parts, bytes.into());
27619
27620                        if let common::Retry::After(d) =
27621                            dlg.http_failure(&response, error.as_ref().ok())
27622                        {
27623                            sleep(d).await;
27624                            continue;
27625                        }
27626
27627                        dlg.finished(false);
27628
27629                        return Err(match error {
27630                            Ok(value) => common::Error::BadRequest(value),
27631                            _ => common::Error::Failure(response),
27632                        });
27633                    }
27634                    let response = {
27635                        let bytes = common::to_bytes(body).await.unwrap_or_default();
27636                        let encoded = common::to_string(&bytes);
27637                        match serde_json::from_str(&encoded) {
27638                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
27639                            Err(error) => {
27640                                dlg.response_json_decode_error(&encoded, &error);
27641                                return Err(common::Error::JsonDecodeError(
27642                                    encoded.to_string(),
27643                                    error,
27644                                ));
27645                            }
27646                        }
27647                    };
27648
27649                    dlg.finished(true);
27650                    return Ok(response);
27651                }
27652            }
27653        }
27654    }
27655
27656    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
27657    ///
27658    /// Sets the *user id* path property to the given value.
27659    ///
27660    /// Even though the property as already been set when instantiating this call,
27661    /// we provide this method for API completeness.
27662    pub fn user_id(mut self, new_value: &str) -> UserThreadTrashCall<'a, C> {
27663        self._user_id = new_value.to_string();
27664        self
27665    }
27666    /// The ID of the thread to Trash.
27667    ///
27668    /// Sets the *id* path property to the given value.
27669    ///
27670    /// Even though the property as already been set when instantiating this call,
27671    /// we provide this method for API completeness.
27672    pub fn id(mut self, new_value: &str) -> UserThreadTrashCall<'a, C> {
27673        self._id = new_value.to_string();
27674        self
27675    }
27676    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
27677    /// while executing the actual API request.
27678    ///
27679    /// ````text
27680    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
27681    /// ````
27682    ///
27683    /// Sets the *delegate* property to the given value.
27684    pub fn delegate(
27685        mut self,
27686        new_value: &'a mut dyn common::Delegate,
27687    ) -> UserThreadTrashCall<'a, C> {
27688        self._delegate = Some(new_value);
27689        self
27690    }
27691
27692    /// Set any additional parameter of the query string used in the request.
27693    /// It should be used to set parameters which are not yet available through their own
27694    /// setters.
27695    ///
27696    /// Please note that this method must not be used to set any of the known parameters
27697    /// which have their own setter method. If done anyway, the request will fail.
27698    ///
27699    /// # Additional Parameters
27700    ///
27701    /// * *$.xgafv* (query-string) - V1 error format.
27702    /// * *access_token* (query-string) - OAuth access token.
27703    /// * *alt* (query-string) - Data format for response.
27704    /// * *callback* (query-string) - JSONP
27705    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
27706    /// * *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.
27707    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
27708    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
27709    /// * *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.
27710    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
27711    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
27712    pub fn param<T>(mut self, name: T, value: T) -> UserThreadTrashCall<'a, C>
27713    where
27714        T: AsRef<str>,
27715    {
27716        self._additional_params
27717            .insert(name.as_ref().to_string(), value.as_ref().to_string());
27718        self
27719    }
27720
27721    /// Identifies the authorization scope for the method you are building.
27722    ///
27723    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
27724    /// [`Scope::Gmai`].
27725    ///
27726    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
27727    /// tokens for more than one scope.
27728    ///
27729    /// Usually there is more than one suitable scope to authorize an operation, some of which may
27730    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
27731    /// sufficient, a read-write scope will do as well.
27732    pub fn add_scope<St>(mut self, scope: St) -> UserThreadTrashCall<'a, C>
27733    where
27734        St: AsRef<str>,
27735    {
27736        self._scopes.insert(String::from(scope.as_ref()));
27737        self
27738    }
27739    /// Identifies the authorization scope(s) for the method you are building.
27740    ///
27741    /// See [`Self::add_scope()`] for details.
27742    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserThreadTrashCall<'a, C>
27743    where
27744        I: IntoIterator<Item = St>,
27745        St: AsRef<str>,
27746    {
27747        self._scopes
27748            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
27749        self
27750    }
27751
27752    /// Removes all scopes, and no default scope will be used either.
27753    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
27754    /// for details).
27755    pub fn clear_scopes(mut self) -> UserThreadTrashCall<'a, C> {
27756        self._scopes.clear();
27757        self
27758    }
27759}
27760
27761/// Removes the specified thread from the trash. Any messages that belong to the thread are also removed from the trash.
27762///
27763/// A builder for the *threads.untrash* method supported by a *user* resource.
27764/// It is not used directly, but through a [`UserMethods`] instance.
27765///
27766/// # Example
27767///
27768/// Instantiate a resource method builder
27769///
27770/// ```test_harness,no_run
27771/// # extern crate hyper;
27772/// # extern crate hyper_rustls;
27773/// # extern crate google_gmail1 as gmail1;
27774/// # async fn dox() {
27775/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
27776///
27777/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
27778/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
27779/// #     secret,
27780/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
27781/// # ).build().await.unwrap();
27782///
27783/// # let client = hyper_util::client::legacy::Client::builder(
27784/// #     hyper_util::rt::TokioExecutor::new()
27785/// # )
27786/// # .build(
27787/// #     hyper_rustls::HttpsConnectorBuilder::new()
27788/// #         .with_native_roots()
27789/// #         .unwrap()
27790/// #         .https_or_http()
27791/// #         .enable_http1()
27792/// #         .build()
27793/// # );
27794/// # let mut hub = Gmail::new(client, auth);
27795/// // You can configure optional parameters by calling the respective setters at will, and
27796/// // execute the final call using `doit()`.
27797/// // Values shown here are possibly random and not representative !
27798/// let result = hub.users().threads_untrash("userId", "id")
27799///              .doit().await;
27800/// # }
27801/// ```
27802pub struct UserThreadUntrashCall<'a, C>
27803where
27804    C: 'a,
27805{
27806    hub: &'a Gmail<C>,
27807    _user_id: String,
27808    _id: String,
27809    _delegate: Option<&'a mut dyn common::Delegate>,
27810    _additional_params: HashMap<String, String>,
27811    _scopes: BTreeSet<String>,
27812}
27813
27814impl<'a, C> common::CallBuilder for UserThreadUntrashCall<'a, C> {}
27815
27816impl<'a, C> UserThreadUntrashCall<'a, C>
27817where
27818    C: common::Connector,
27819{
27820    /// Perform the operation you have build so far.
27821    pub async fn doit(mut self) -> common::Result<(common::Response, Thread)> {
27822        use std::borrow::Cow;
27823        use std::io::{Read, Seek};
27824
27825        use common::{url::Params, ToParts};
27826        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
27827
27828        let mut dd = common::DefaultDelegate;
27829        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
27830        dlg.begin(common::MethodInfo {
27831            id: "gmail.users.threads.untrash",
27832            http_method: hyper::Method::POST,
27833        });
27834
27835        for &field in ["alt", "userId", "id"].iter() {
27836            if self._additional_params.contains_key(field) {
27837                dlg.finished(false);
27838                return Err(common::Error::FieldClash(field));
27839            }
27840        }
27841
27842        let mut params = Params::with_capacity(4 + self._additional_params.len());
27843        params.push("userId", self._user_id);
27844        params.push("id", self._id);
27845
27846        params.extend(self._additional_params.iter());
27847
27848        params.push("alt", "json");
27849        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/threads/{id}/untrash";
27850        if self._scopes.is_empty() {
27851            self._scopes.insert(Scope::Gmai.as_ref().to_string());
27852        }
27853
27854        #[allow(clippy::single_element_loop)]
27855        for &(find_this, param_name) in [("{userId}", "userId"), ("{id}", "id")].iter() {
27856            url = params.uri_replacement(url, param_name, find_this, false);
27857        }
27858        {
27859            let to_remove = ["id", "userId"];
27860            params.remove_params(&to_remove);
27861        }
27862
27863        let url = params.parse_with_url(&url);
27864
27865        loop {
27866            let token = match self
27867                .hub
27868                .auth
27869                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
27870                .await
27871            {
27872                Ok(token) => token,
27873                Err(e) => match dlg.token(e) {
27874                    Ok(token) => token,
27875                    Err(e) => {
27876                        dlg.finished(false);
27877                        return Err(common::Error::MissingToken(e));
27878                    }
27879                },
27880            };
27881            let mut req_result = {
27882                let client = &self.hub.client;
27883                dlg.pre_request();
27884                let mut req_builder = hyper::Request::builder()
27885                    .method(hyper::Method::POST)
27886                    .uri(url.as_str())
27887                    .header(USER_AGENT, self.hub._user_agent.clone());
27888
27889                if let Some(token) = token.as_ref() {
27890                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
27891                }
27892
27893                let request = req_builder
27894                    .header(CONTENT_LENGTH, 0_u64)
27895                    .body(common::to_body::<String>(None));
27896
27897                client.request(request.unwrap()).await
27898            };
27899
27900            match req_result {
27901                Err(err) => {
27902                    if let common::Retry::After(d) = dlg.http_error(&err) {
27903                        sleep(d).await;
27904                        continue;
27905                    }
27906                    dlg.finished(false);
27907                    return Err(common::Error::HttpError(err));
27908                }
27909                Ok(res) => {
27910                    let (mut parts, body) = res.into_parts();
27911                    let mut body = common::Body::new(body);
27912                    if !parts.status.is_success() {
27913                        let bytes = common::to_bytes(body).await.unwrap_or_default();
27914                        let error = serde_json::from_str(&common::to_string(&bytes));
27915                        let response = common::to_response(parts, bytes.into());
27916
27917                        if let common::Retry::After(d) =
27918                            dlg.http_failure(&response, error.as_ref().ok())
27919                        {
27920                            sleep(d).await;
27921                            continue;
27922                        }
27923
27924                        dlg.finished(false);
27925
27926                        return Err(match error {
27927                            Ok(value) => common::Error::BadRequest(value),
27928                            _ => common::Error::Failure(response),
27929                        });
27930                    }
27931                    let response = {
27932                        let bytes = common::to_bytes(body).await.unwrap_or_default();
27933                        let encoded = common::to_string(&bytes);
27934                        match serde_json::from_str(&encoded) {
27935                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
27936                            Err(error) => {
27937                                dlg.response_json_decode_error(&encoded, &error);
27938                                return Err(common::Error::JsonDecodeError(
27939                                    encoded.to_string(),
27940                                    error,
27941                                ));
27942                            }
27943                        }
27944                    };
27945
27946                    dlg.finished(true);
27947                    return Ok(response);
27948                }
27949            }
27950        }
27951    }
27952
27953    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
27954    ///
27955    /// Sets the *user id* path property to the given value.
27956    ///
27957    /// Even though the property as already been set when instantiating this call,
27958    /// we provide this method for API completeness.
27959    pub fn user_id(mut self, new_value: &str) -> UserThreadUntrashCall<'a, C> {
27960        self._user_id = new_value.to_string();
27961        self
27962    }
27963    /// The ID of the thread to remove from Trash.
27964    ///
27965    /// Sets the *id* path property to the given value.
27966    ///
27967    /// Even though the property as already been set when instantiating this call,
27968    /// we provide this method for API completeness.
27969    pub fn id(mut self, new_value: &str) -> UserThreadUntrashCall<'a, C> {
27970        self._id = new_value.to_string();
27971        self
27972    }
27973    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
27974    /// while executing the actual API request.
27975    ///
27976    /// ````text
27977    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
27978    /// ````
27979    ///
27980    /// Sets the *delegate* property to the given value.
27981    pub fn delegate(
27982        mut self,
27983        new_value: &'a mut dyn common::Delegate,
27984    ) -> UserThreadUntrashCall<'a, C> {
27985        self._delegate = Some(new_value);
27986        self
27987    }
27988
27989    /// Set any additional parameter of the query string used in the request.
27990    /// It should be used to set parameters which are not yet available through their own
27991    /// setters.
27992    ///
27993    /// Please note that this method must not be used to set any of the known parameters
27994    /// which have their own setter method. If done anyway, the request will fail.
27995    ///
27996    /// # Additional Parameters
27997    ///
27998    /// * *$.xgafv* (query-string) - V1 error format.
27999    /// * *access_token* (query-string) - OAuth access token.
28000    /// * *alt* (query-string) - Data format for response.
28001    /// * *callback* (query-string) - JSONP
28002    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
28003    /// * *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.
28004    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
28005    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
28006    /// * *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.
28007    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
28008    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
28009    pub fn param<T>(mut self, name: T, value: T) -> UserThreadUntrashCall<'a, C>
28010    where
28011        T: AsRef<str>,
28012    {
28013        self._additional_params
28014            .insert(name.as_ref().to_string(), value.as_ref().to_string());
28015        self
28016    }
28017
28018    /// Identifies the authorization scope for the method you are building.
28019    ///
28020    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
28021    /// [`Scope::Gmai`].
28022    ///
28023    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
28024    /// tokens for more than one scope.
28025    ///
28026    /// Usually there is more than one suitable scope to authorize an operation, some of which may
28027    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
28028    /// sufficient, a read-write scope will do as well.
28029    pub fn add_scope<St>(mut self, scope: St) -> UserThreadUntrashCall<'a, C>
28030    where
28031        St: AsRef<str>,
28032    {
28033        self._scopes.insert(String::from(scope.as_ref()));
28034        self
28035    }
28036    /// Identifies the authorization scope(s) for the method you are building.
28037    ///
28038    /// See [`Self::add_scope()`] for details.
28039    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserThreadUntrashCall<'a, C>
28040    where
28041        I: IntoIterator<Item = St>,
28042        St: AsRef<str>,
28043    {
28044        self._scopes
28045            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
28046        self
28047    }
28048
28049    /// Removes all scopes, and no default scope will be used either.
28050    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
28051    /// for details).
28052    pub fn clear_scopes(mut self) -> UserThreadUntrashCall<'a, C> {
28053        self._scopes.clear();
28054        self
28055    }
28056}
28057
28058/// Gets the current user's Gmail profile.
28059///
28060/// A builder for the *getProfile* method supported by a *user* resource.
28061/// It is not used directly, but through a [`UserMethods`] instance.
28062///
28063/// # Example
28064///
28065/// Instantiate a resource method builder
28066///
28067/// ```test_harness,no_run
28068/// # extern crate hyper;
28069/// # extern crate hyper_rustls;
28070/// # extern crate google_gmail1 as gmail1;
28071/// # async fn dox() {
28072/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
28073///
28074/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
28075/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
28076/// #     secret,
28077/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
28078/// # ).build().await.unwrap();
28079///
28080/// # let client = hyper_util::client::legacy::Client::builder(
28081/// #     hyper_util::rt::TokioExecutor::new()
28082/// # )
28083/// # .build(
28084/// #     hyper_rustls::HttpsConnectorBuilder::new()
28085/// #         .with_native_roots()
28086/// #         .unwrap()
28087/// #         .https_or_http()
28088/// #         .enable_http1()
28089/// #         .build()
28090/// # );
28091/// # let mut hub = Gmail::new(client, auth);
28092/// // You can configure optional parameters by calling the respective setters at will, and
28093/// // execute the final call using `doit()`.
28094/// // Values shown here are possibly random and not representative !
28095/// let result = hub.users().get_profile("userId")
28096///              .doit().await;
28097/// # }
28098/// ```
28099pub struct UserGetProfileCall<'a, C>
28100where
28101    C: 'a,
28102{
28103    hub: &'a Gmail<C>,
28104    _user_id: String,
28105    _delegate: Option<&'a mut dyn common::Delegate>,
28106    _additional_params: HashMap<String, String>,
28107    _scopes: BTreeSet<String>,
28108}
28109
28110impl<'a, C> common::CallBuilder for UserGetProfileCall<'a, C> {}
28111
28112impl<'a, C> UserGetProfileCall<'a, C>
28113where
28114    C: common::Connector,
28115{
28116    /// Perform the operation you have build so far.
28117    pub async fn doit(mut self) -> common::Result<(common::Response, Profile)> {
28118        use std::borrow::Cow;
28119        use std::io::{Read, Seek};
28120
28121        use common::{url::Params, ToParts};
28122        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
28123
28124        let mut dd = common::DefaultDelegate;
28125        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
28126        dlg.begin(common::MethodInfo {
28127            id: "gmail.users.getProfile",
28128            http_method: hyper::Method::GET,
28129        });
28130
28131        for &field in ["alt", "userId"].iter() {
28132            if self._additional_params.contains_key(field) {
28133                dlg.finished(false);
28134                return Err(common::Error::FieldClash(field));
28135            }
28136        }
28137
28138        let mut params = Params::with_capacity(3 + self._additional_params.len());
28139        params.push("userId", self._user_id);
28140
28141        params.extend(self._additional_params.iter());
28142
28143        params.push("alt", "json");
28144        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/profile";
28145        if self._scopes.is_empty() {
28146            self._scopes.insert(Scope::Readonly.as_ref().to_string());
28147        }
28148
28149        #[allow(clippy::single_element_loop)]
28150        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
28151            url = params.uri_replacement(url, param_name, find_this, false);
28152        }
28153        {
28154            let to_remove = ["userId"];
28155            params.remove_params(&to_remove);
28156        }
28157
28158        let url = params.parse_with_url(&url);
28159
28160        loop {
28161            let token = match self
28162                .hub
28163                .auth
28164                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
28165                .await
28166            {
28167                Ok(token) => token,
28168                Err(e) => match dlg.token(e) {
28169                    Ok(token) => token,
28170                    Err(e) => {
28171                        dlg.finished(false);
28172                        return Err(common::Error::MissingToken(e));
28173                    }
28174                },
28175            };
28176            let mut req_result = {
28177                let client = &self.hub.client;
28178                dlg.pre_request();
28179                let mut req_builder = hyper::Request::builder()
28180                    .method(hyper::Method::GET)
28181                    .uri(url.as_str())
28182                    .header(USER_AGENT, self.hub._user_agent.clone());
28183
28184                if let Some(token) = token.as_ref() {
28185                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
28186                }
28187
28188                let request = req_builder
28189                    .header(CONTENT_LENGTH, 0_u64)
28190                    .body(common::to_body::<String>(None));
28191
28192                client.request(request.unwrap()).await
28193            };
28194
28195            match req_result {
28196                Err(err) => {
28197                    if let common::Retry::After(d) = dlg.http_error(&err) {
28198                        sleep(d).await;
28199                        continue;
28200                    }
28201                    dlg.finished(false);
28202                    return Err(common::Error::HttpError(err));
28203                }
28204                Ok(res) => {
28205                    let (mut parts, body) = res.into_parts();
28206                    let mut body = common::Body::new(body);
28207                    if !parts.status.is_success() {
28208                        let bytes = common::to_bytes(body).await.unwrap_or_default();
28209                        let error = serde_json::from_str(&common::to_string(&bytes));
28210                        let response = common::to_response(parts, bytes.into());
28211
28212                        if let common::Retry::After(d) =
28213                            dlg.http_failure(&response, error.as_ref().ok())
28214                        {
28215                            sleep(d).await;
28216                            continue;
28217                        }
28218
28219                        dlg.finished(false);
28220
28221                        return Err(match error {
28222                            Ok(value) => common::Error::BadRequest(value),
28223                            _ => common::Error::Failure(response),
28224                        });
28225                    }
28226                    let response = {
28227                        let bytes = common::to_bytes(body).await.unwrap_or_default();
28228                        let encoded = common::to_string(&bytes);
28229                        match serde_json::from_str(&encoded) {
28230                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
28231                            Err(error) => {
28232                                dlg.response_json_decode_error(&encoded, &error);
28233                                return Err(common::Error::JsonDecodeError(
28234                                    encoded.to_string(),
28235                                    error,
28236                                ));
28237                            }
28238                        }
28239                    };
28240
28241                    dlg.finished(true);
28242                    return Ok(response);
28243                }
28244            }
28245        }
28246    }
28247
28248    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
28249    ///
28250    /// Sets the *user id* path property to the given value.
28251    ///
28252    /// Even though the property as already been set when instantiating this call,
28253    /// we provide this method for API completeness.
28254    pub fn user_id(mut self, new_value: &str) -> UserGetProfileCall<'a, C> {
28255        self._user_id = new_value.to_string();
28256        self
28257    }
28258    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
28259    /// while executing the actual API request.
28260    ///
28261    /// ````text
28262    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
28263    /// ````
28264    ///
28265    /// Sets the *delegate* property to the given value.
28266    pub fn delegate(
28267        mut self,
28268        new_value: &'a mut dyn common::Delegate,
28269    ) -> UserGetProfileCall<'a, C> {
28270        self._delegate = Some(new_value);
28271        self
28272    }
28273
28274    /// Set any additional parameter of the query string used in the request.
28275    /// It should be used to set parameters which are not yet available through their own
28276    /// setters.
28277    ///
28278    /// Please note that this method must not be used to set any of the known parameters
28279    /// which have their own setter method. If done anyway, the request will fail.
28280    ///
28281    /// # Additional Parameters
28282    ///
28283    /// * *$.xgafv* (query-string) - V1 error format.
28284    /// * *access_token* (query-string) - OAuth access token.
28285    /// * *alt* (query-string) - Data format for response.
28286    /// * *callback* (query-string) - JSONP
28287    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
28288    /// * *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.
28289    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
28290    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
28291    /// * *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.
28292    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
28293    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
28294    pub fn param<T>(mut self, name: T, value: T) -> UserGetProfileCall<'a, C>
28295    where
28296        T: AsRef<str>,
28297    {
28298        self._additional_params
28299            .insert(name.as_ref().to_string(), value.as_ref().to_string());
28300        self
28301    }
28302
28303    /// Identifies the authorization scope for the method you are building.
28304    ///
28305    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
28306    /// [`Scope::Readonly`].
28307    ///
28308    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
28309    /// tokens for more than one scope.
28310    ///
28311    /// Usually there is more than one suitable scope to authorize an operation, some of which may
28312    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
28313    /// sufficient, a read-write scope will do as well.
28314    pub fn add_scope<St>(mut self, scope: St) -> UserGetProfileCall<'a, C>
28315    where
28316        St: AsRef<str>,
28317    {
28318        self._scopes.insert(String::from(scope.as_ref()));
28319        self
28320    }
28321    /// Identifies the authorization scope(s) for the method you are building.
28322    ///
28323    /// See [`Self::add_scope()`] for details.
28324    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserGetProfileCall<'a, C>
28325    where
28326        I: IntoIterator<Item = St>,
28327        St: AsRef<str>,
28328    {
28329        self._scopes
28330            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
28331        self
28332    }
28333
28334    /// Removes all scopes, and no default scope will be used either.
28335    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
28336    /// for details).
28337    pub fn clear_scopes(mut self) -> UserGetProfileCall<'a, C> {
28338        self._scopes.clear();
28339        self
28340    }
28341}
28342
28343/// Stop receiving push notifications for the given user mailbox.
28344///
28345/// A builder for the *stop* method supported by a *user* resource.
28346/// It is not used directly, but through a [`UserMethods`] instance.
28347///
28348/// # Example
28349///
28350/// Instantiate a resource method builder
28351///
28352/// ```test_harness,no_run
28353/// # extern crate hyper;
28354/// # extern crate hyper_rustls;
28355/// # extern crate google_gmail1 as gmail1;
28356/// # async fn dox() {
28357/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
28358///
28359/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
28360/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
28361/// #     secret,
28362/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
28363/// # ).build().await.unwrap();
28364///
28365/// # let client = hyper_util::client::legacy::Client::builder(
28366/// #     hyper_util::rt::TokioExecutor::new()
28367/// # )
28368/// # .build(
28369/// #     hyper_rustls::HttpsConnectorBuilder::new()
28370/// #         .with_native_roots()
28371/// #         .unwrap()
28372/// #         .https_or_http()
28373/// #         .enable_http1()
28374/// #         .build()
28375/// # );
28376/// # let mut hub = Gmail::new(client, auth);
28377/// // You can configure optional parameters by calling the respective setters at will, and
28378/// // execute the final call using `doit()`.
28379/// // Values shown here are possibly random and not representative !
28380/// let result = hub.users().stop("userId")
28381///              .doit().await;
28382/// # }
28383/// ```
28384pub struct UserStopCall<'a, C>
28385where
28386    C: 'a,
28387{
28388    hub: &'a Gmail<C>,
28389    _user_id: String,
28390    _delegate: Option<&'a mut dyn common::Delegate>,
28391    _additional_params: HashMap<String, String>,
28392    _scopes: BTreeSet<String>,
28393}
28394
28395impl<'a, C> common::CallBuilder for UserStopCall<'a, C> {}
28396
28397impl<'a, C> UserStopCall<'a, C>
28398where
28399    C: common::Connector,
28400{
28401    /// Perform the operation you have build so far.
28402    pub async fn doit(mut self) -> common::Result<common::Response> {
28403        use std::borrow::Cow;
28404        use std::io::{Read, Seek};
28405
28406        use common::{url::Params, ToParts};
28407        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
28408
28409        let mut dd = common::DefaultDelegate;
28410        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
28411        dlg.begin(common::MethodInfo {
28412            id: "gmail.users.stop",
28413            http_method: hyper::Method::POST,
28414        });
28415
28416        for &field in ["userId"].iter() {
28417            if self._additional_params.contains_key(field) {
28418                dlg.finished(false);
28419                return Err(common::Error::FieldClash(field));
28420            }
28421        }
28422
28423        let mut params = Params::with_capacity(2 + self._additional_params.len());
28424        params.push("userId", self._user_id);
28425
28426        params.extend(self._additional_params.iter());
28427
28428        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/stop";
28429        if self._scopes.is_empty() {
28430            self._scopes.insert(Scope::Gmai.as_ref().to_string());
28431        }
28432
28433        #[allow(clippy::single_element_loop)]
28434        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
28435            url = params.uri_replacement(url, param_name, find_this, false);
28436        }
28437        {
28438            let to_remove = ["userId"];
28439            params.remove_params(&to_remove);
28440        }
28441
28442        let url = params.parse_with_url(&url);
28443
28444        loop {
28445            let token = match self
28446                .hub
28447                .auth
28448                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
28449                .await
28450            {
28451                Ok(token) => token,
28452                Err(e) => match dlg.token(e) {
28453                    Ok(token) => token,
28454                    Err(e) => {
28455                        dlg.finished(false);
28456                        return Err(common::Error::MissingToken(e));
28457                    }
28458                },
28459            };
28460            let mut req_result = {
28461                let client = &self.hub.client;
28462                dlg.pre_request();
28463                let mut req_builder = hyper::Request::builder()
28464                    .method(hyper::Method::POST)
28465                    .uri(url.as_str())
28466                    .header(USER_AGENT, self.hub._user_agent.clone());
28467
28468                if let Some(token) = token.as_ref() {
28469                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
28470                }
28471
28472                let request = req_builder
28473                    .header(CONTENT_LENGTH, 0_u64)
28474                    .body(common::to_body::<String>(None));
28475
28476                client.request(request.unwrap()).await
28477            };
28478
28479            match req_result {
28480                Err(err) => {
28481                    if let common::Retry::After(d) = dlg.http_error(&err) {
28482                        sleep(d).await;
28483                        continue;
28484                    }
28485                    dlg.finished(false);
28486                    return Err(common::Error::HttpError(err));
28487                }
28488                Ok(res) => {
28489                    let (mut parts, body) = res.into_parts();
28490                    let mut body = common::Body::new(body);
28491                    if !parts.status.is_success() {
28492                        let bytes = common::to_bytes(body).await.unwrap_or_default();
28493                        let error = serde_json::from_str(&common::to_string(&bytes));
28494                        let response = common::to_response(parts, bytes.into());
28495
28496                        if let common::Retry::After(d) =
28497                            dlg.http_failure(&response, error.as_ref().ok())
28498                        {
28499                            sleep(d).await;
28500                            continue;
28501                        }
28502
28503                        dlg.finished(false);
28504
28505                        return Err(match error {
28506                            Ok(value) => common::Error::BadRequest(value),
28507                            _ => common::Error::Failure(response),
28508                        });
28509                    }
28510                    let response = common::Response::from_parts(parts, body);
28511
28512                    dlg.finished(true);
28513                    return Ok(response);
28514                }
28515            }
28516        }
28517    }
28518
28519    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
28520    ///
28521    /// Sets the *user id* path property to the given value.
28522    ///
28523    /// Even though the property as already been set when instantiating this call,
28524    /// we provide this method for API completeness.
28525    pub fn user_id(mut self, new_value: &str) -> UserStopCall<'a, C> {
28526        self._user_id = new_value.to_string();
28527        self
28528    }
28529    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
28530    /// while executing the actual API request.
28531    ///
28532    /// ````text
28533    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
28534    /// ````
28535    ///
28536    /// Sets the *delegate* property to the given value.
28537    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> UserStopCall<'a, C> {
28538        self._delegate = Some(new_value);
28539        self
28540    }
28541
28542    /// Set any additional parameter of the query string used in the request.
28543    /// It should be used to set parameters which are not yet available through their own
28544    /// setters.
28545    ///
28546    /// Please note that this method must not be used to set any of the known parameters
28547    /// which have their own setter method. If done anyway, the request will fail.
28548    ///
28549    /// # Additional Parameters
28550    ///
28551    /// * *$.xgafv* (query-string) - V1 error format.
28552    /// * *access_token* (query-string) - OAuth access token.
28553    /// * *alt* (query-string) - Data format for response.
28554    /// * *callback* (query-string) - JSONP
28555    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
28556    /// * *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.
28557    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
28558    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
28559    /// * *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.
28560    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
28561    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
28562    pub fn param<T>(mut self, name: T, value: T) -> UserStopCall<'a, C>
28563    where
28564        T: AsRef<str>,
28565    {
28566        self._additional_params
28567            .insert(name.as_ref().to_string(), value.as_ref().to_string());
28568        self
28569    }
28570
28571    /// Identifies the authorization scope for the method you are building.
28572    ///
28573    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
28574    /// [`Scope::Gmai`].
28575    ///
28576    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
28577    /// tokens for more than one scope.
28578    ///
28579    /// Usually there is more than one suitable scope to authorize an operation, some of which may
28580    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
28581    /// sufficient, a read-write scope will do as well.
28582    pub fn add_scope<St>(mut self, scope: St) -> UserStopCall<'a, C>
28583    where
28584        St: AsRef<str>,
28585    {
28586        self._scopes.insert(String::from(scope.as_ref()));
28587        self
28588    }
28589    /// Identifies the authorization scope(s) for the method you are building.
28590    ///
28591    /// See [`Self::add_scope()`] for details.
28592    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserStopCall<'a, C>
28593    where
28594        I: IntoIterator<Item = St>,
28595        St: AsRef<str>,
28596    {
28597        self._scopes
28598            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
28599        self
28600    }
28601
28602    /// Removes all scopes, and no default scope will be used either.
28603    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
28604    /// for details).
28605    pub fn clear_scopes(mut self) -> UserStopCall<'a, C> {
28606        self._scopes.clear();
28607        self
28608    }
28609}
28610
28611/// Set up or update a push notification watch on the given user mailbox.
28612///
28613/// A builder for the *watch* method supported by a *user* resource.
28614/// It is not used directly, but through a [`UserMethods`] instance.
28615///
28616/// # Example
28617///
28618/// Instantiate a resource method builder
28619///
28620/// ```test_harness,no_run
28621/// # extern crate hyper;
28622/// # extern crate hyper_rustls;
28623/// # extern crate google_gmail1 as gmail1;
28624/// use gmail1::api::WatchRequest;
28625/// # async fn dox() {
28626/// # use gmail1::{Gmail, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
28627///
28628/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
28629/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
28630/// #     secret,
28631/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
28632/// # ).build().await.unwrap();
28633///
28634/// # let client = hyper_util::client::legacy::Client::builder(
28635/// #     hyper_util::rt::TokioExecutor::new()
28636/// # )
28637/// # .build(
28638/// #     hyper_rustls::HttpsConnectorBuilder::new()
28639/// #         .with_native_roots()
28640/// #         .unwrap()
28641/// #         .https_or_http()
28642/// #         .enable_http1()
28643/// #         .build()
28644/// # );
28645/// # let mut hub = Gmail::new(client, auth);
28646/// // As the method needs a request, you would usually fill it with the desired information
28647/// // into the respective structure. Some of the parts shown here might not be applicable !
28648/// // Values shown here are possibly random and not representative !
28649/// let mut req = WatchRequest::default();
28650///
28651/// // You can configure optional parameters by calling the respective setters at will, and
28652/// // execute the final call using `doit()`.
28653/// // Values shown here are possibly random and not representative !
28654/// let result = hub.users().watch(req, "userId")
28655///              .doit().await;
28656/// # }
28657/// ```
28658pub struct UserWatchCall<'a, C>
28659where
28660    C: 'a,
28661{
28662    hub: &'a Gmail<C>,
28663    _request: WatchRequest,
28664    _user_id: String,
28665    _delegate: Option<&'a mut dyn common::Delegate>,
28666    _additional_params: HashMap<String, String>,
28667    _scopes: BTreeSet<String>,
28668}
28669
28670impl<'a, C> common::CallBuilder for UserWatchCall<'a, C> {}
28671
28672impl<'a, C> UserWatchCall<'a, C>
28673where
28674    C: common::Connector,
28675{
28676    /// Perform the operation you have build so far.
28677    pub async fn doit(mut self) -> common::Result<(common::Response, WatchResponse)> {
28678        use std::borrow::Cow;
28679        use std::io::{Read, Seek};
28680
28681        use common::{url::Params, ToParts};
28682        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
28683
28684        let mut dd = common::DefaultDelegate;
28685        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
28686        dlg.begin(common::MethodInfo {
28687            id: "gmail.users.watch",
28688            http_method: hyper::Method::POST,
28689        });
28690
28691        for &field in ["alt", "userId"].iter() {
28692            if self._additional_params.contains_key(field) {
28693                dlg.finished(false);
28694                return Err(common::Error::FieldClash(field));
28695            }
28696        }
28697
28698        let mut params = Params::with_capacity(4 + self._additional_params.len());
28699        params.push("userId", self._user_id);
28700
28701        params.extend(self._additional_params.iter());
28702
28703        params.push("alt", "json");
28704        let mut url = self.hub._base_url.clone() + "gmail/v1/users/{userId}/watch";
28705        if self._scopes.is_empty() {
28706            self._scopes.insert(Scope::Gmai.as_ref().to_string());
28707        }
28708
28709        #[allow(clippy::single_element_loop)]
28710        for &(find_this, param_name) in [("{userId}", "userId")].iter() {
28711            url = params.uri_replacement(url, param_name, find_this, false);
28712        }
28713        {
28714            let to_remove = ["userId"];
28715            params.remove_params(&to_remove);
28716        }
28717
28718        let url = params.parse_with_url(&url);
28719
28720        let mut json_mime_type = mime::APPLICATION_JSON;
28721        let mut request_value_reader = {
28722            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
28723            common::remove_json_null_values(&mut value);
28724            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
28725            serde_json::to_writer(&mut dst, &value).unwrap();
28726            dst
28727        };
28728        let request_size = request_value_reader
28729            .seek(std::io::SeekFrom::End(0))
28730            .unwrap();
28731        request_value_reader
28732            .seek(std::io::SeekFrom::Start(0))
28733            .unwrap();
28734
28735        loop {
28736            let token = match self
28737                .hub
28738                .auth
28739                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
28740                .await
28741            {
28742                Ok(token) => token,
28743                Err(e) => match dlg.token(e) {
28744                    Ok(token) => token,
28745                    Err(e) => {
28746                        dlg.finished(false);
28747                        return Err(common::Error::MissingToken(e));
28748                    }
28749                },
28750            };
28751            request_value_reader
28752                .seek(std::io::SeekFrom::Start(0))
28753                .unwrap();
28754            let mut req_result = {
28755                let client = &self.hub.client;
28756                dlg.pre_request();
28757                let mut req_builder = hyper::Request::builder()
28758                    .method(hyper::Method::POST)
28759                    .uri(url.as_str())
28760                    .header(USER_AGENT, self.hub._user_agent.clone());
28761
28762                if let Some(token) = token.as_ref() {
28763                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
28764                }
28765
28766                let request = req_builder
28767                    .header(CONTENT_TYPE, json_mime_type.to_string())
28768                    .header(CONTENT_LENGTH, request_size as u64)
28769                    .body(common::to_body(
28770                        request_value_reader.get_ref().clone().into(),
28771                    ));
28772
28773                client.request(request.unwrap()).await
28774            };
28775
28776            match req_result {
28777                Err(err) => {
28778                    if let common::Retry::After(d) = dlg.http_error(&err) {
28779                        sleep(d).await;
28780                        continue;
28781                    }
28782                    dlg.finished(false);
28783                    return Err(common::Error::HttpError(err));
28784                }
28785                Ok(res) => {
28786                    let (mut parts, body) = res.into_parts();
28787                    let mut body = common::Body::new(body);
28788                    if !parts.status.is_success() {
28789                        let bytes = common::to_bytes(body).await.unwrap_or_default();
28790                        let error = serde_json::from_str(&common::to_string(&bytes));
28791                        let response = common::to_response(parts, bytes.into());
28792
28793                        if let common::Retry::After(d) =
28794                            dlg.http_failure(&response, error.as_ref().ok())
28795                        {
28796                            sleep(d).await;
28797                            continue;
28798                        }
28799
28800                        dlg.finished(false);
28801
28802                        return Err(match error {
28803                            Ok(value) => common::Error::BadRequest(value),
28804                            _ => common::Error::Failure(response),
28805                        });
28806                    }
28807                    let response = {
28808                        let bytes = common::to_bytes(body).await.unwrap_or_default();
28809                        let encoded = common::to_string(&bytes);
28810                        match serde_json::from_str(&encoded) {
28811                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
28812                            Err(error) => {
28813                                dlg.response_json_decode_error(&encoded, &error);
28814                                return Err(common::Error::JsonDecodeError(
28815                                    encoded.to_string(),
28816                                    error,
28817                                ));
28818                            }
28819                        }
28820                    };
28821
28822                    dlg.finished(true);
28823                    return Ok(response);
28824                }
28825            }
28826        }
28827    }
28828
28829    ///
28830    /// Sets the *request* property to the given value.
28831    ///
28832    /// Even though the property as already been set when instantiating this call,
28833    /// we provide this method for API completeness.
28834    pub fn request(mut self, new_value: WatchRequest) -> UserWatchCall<'a, C> {
28835        self._request = new_value;
28836        self
28837    }
28838    /// The user's email address. The special value `me` can be used to indicate the authenticated user.
28839    ///
28840    /// Sets the *user id* path property to the given value.
28841    ///
28842    /// Even though the property as already been set when instantiating this call,
28843    /// we provide this method for API completeness.
28844    pub fn user_id(mut self, new_value: &str) -> UserWatchCall<'a, C> {
28845        self._user_id = new_value.to_string();
28846        self
28847    }
28848    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
28849    /// while executing the actual API request.
28850    ///
28851    /// ````text
28852    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
28853    /// ````
28854    ///
28855    /// Sets the *delegate* property to the given value.
28856    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> UserWatchCall<'a, C> {
28857        self._delegate = Some(new_value);
28858        self
28859    }
28860
28861    /// Set any additional parameter of the query string used in the request.
28862    /// It should be used to set parameters which are not yet available through their own
28863    /// setters.
28864    ///
28865    /// Please note that this method must not be used to set any of the known parameters
28866    /// which have their own setter method. If done anyway, the request will fail.
28867    ///
28868    /// # Additional Parameters
28869    ///
28870    /// * *$.xgafv* (query-string) - V1 error format.
28871    /// * *access_token* (query-string) - OAuth access token.
28872    /// * *alt* (query-string) - Data format for response.
28873    /// * *callback* (query-string) - JSONP
28874    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
28875    /// * *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.
28876    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
28877    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
28878    /// * *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.
28879    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
28880    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
28881    pub fn param<T>(mut self, name: T, value: T) -> UserWatchCall<'a, C>
28882    where
28883        T: AsRef<str>,
28884    {
28885        self._additional_params
28886            .insert(name.as_ref().to_string(), value.as_ref().to_string());
28887        self
28888    }
28889
28890    /// Identifies the authorization scope for the method you are building.
28891    ///
28892    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
28893    /// [`Scope::Gmai`].
28894    ///
28895    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
28896    /// tokens for more than one scope.
28897    ///
28898    /// Usually there is more than one suitable scope to authorize an operation, some of which may
28899    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
28900    /// sufficient, a read-write scope will do as well.
28901    pub fn add_scope<St>(mut self, scope: St) -> UserWatchCall<'a, C>
28902    where
28903        St: AsRef<str>,
28904    {
28905        self._scopes.insert(String::from(scope.as_ref()));
28906        self
28907    }
28908    /// Identifies the authorization scope(s) for the method you are building.
28909    ///
28910    /// See [`Self::add_scope()`] for details.
28911    pub fn add_scopes<I, St>(mut self, scopes: I) -> UserWatchCall<'a, C>
28912    where
28913        I: IntoIterator<Item = St>,
28914        St: AsRef<str>,
28915    {
28916        self._scopes
28917            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
28918        self
28919    }
28920
28921    /// Removes all scopes, and no default scope will be used either.
28922    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
28923    /// for details).
28924    pub fn clear_scopes(mut self) -> UserWatchCall<'a, C> {
28925        self._scopes.clear();
28926        self
28927    }
28928}