google_gmailpostmastertools1/api.rs
1#![allow(clippy::ptr_arg)]
2
3use std::collections::{BTreeSet, HashMap};
4
5use tokio::time::sleep;
6
7// ##############
8// UTILITIES ###
9// ############
10
11/// Identifies the an OAuth2 authorization scope.
12/// A scope is needed when requesting an
13/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
14#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
15pub enum Scope {
16 /// See email traffic metrics for the domains you have registered in Gmail Postmaster Tools
17 PostmasterReadonly,
18}
19
20impl AsRef<str> for Scope {
21 fn as_ref(&self) -> &str {
22 match *self {
23 Scope::PostmasterReadonly => "https://www.googleapis.com/auth/postmaster.readonly",
24 }
25 }
26}
27
28#[allow(clippy::derivable_impls)]
29impl Default for Scope {
30 fn default() -> Scope {
31 Scope::PostmasterReadonly
32 }
33}
34
35// ########
36// HUB ###
37// ######
38
39/// Central instance to access all PostmasterTools related resource activities
40///
41/// # Examples
42///
43/// Instantiate a new hub
44///
45/// ```test_harness,no_run
46/// extern crate hyper;
47/// extern crate hyper_rustls;
48/// extern crate google_gmailpostmastertools1 as gmailpostmastertools1;
49/// use gmailpostmastertools1::{Result, Error};
50/// # async fn dox() {
51/// use gmailpostmastertools1::{PostmasterTools, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
52///
53/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
54/// // `client_secret`, among other things.
55/// let secret: yup_oauth2::ApplicationSecret = Default::default();
56/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
57/// // unless you replace `None` with the desired Flow.
58/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
59/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
60/// // retrieve them from storage.
61/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
62/// .with_native_roots()
63/// .unwrap()
64/// .https_only()
65/// .enable_http2()
66/// .build();
67///
68/// let executor = hyper_util::rt::TokioExecutor::new();
69/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
70/// secret,
71/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
72/// yup_oauth2::client::CustomHyperClientBuilder::from(
73/// hyper_util::client::legacy::Client::builder(executor).build(connector),
74/// ),
75/// ).build().await.unwrap();
76///
77/// let client = hyper_util::client::legacy::Client::builder(
78/// hyper_util::rt::TokioExecutor::new()
79/// )
80/// .build(
81/// hyper_rustls::HttpsConnectorBuilder::new()
82/// .with_native_roots()
83/// .unwrap()
84/// .https_or_http()
85/// .enable_http2()
86/// .build()
87/// );
88/// let mut hub = PostmasterTools::new(client, auth);
89/// // You can configure optional parameters by calling the respective setters at will, and
90/// // execute the final call using `doit()`.
91/// // Values shown here are possibly random and not representative !
92/// let result = hub.domains().traffic_stats_list("parent")
93/// .start_date_year(-55)
94/// .start_date_month(-88)
95/// .start_date_day(-47)
96/// .page_token("duo")
97/// .page_size(-50)
98/// .end_date_year(-93)
99/// .end_date_month(-37)
100/// .end_date_day(-12)
101/// .doit().await;
102///
103/// match result {
104/// Err(e) => match e {
105/// // The Error enum provides details about what exactly happened.
106/// // You can also just use its `Debug`, `Display` or `Error` traits
107/// Error::HttpError(_)
108/// |Error::Io(_)
109/// |Error::MissingAPIKey
110/// |Error::MissingToken(_)
111/// |Error::Cancelled
112/// |Error::UploadSizeLimitExceeded(_, _)
113/// |Error::Failure(_)
114/// |Error::BadRequest(_)
115/// |Error::FieldClash(_)
116/// |Error::JsonDecodeError(_, _) => println!("{}", e),
117/// },
118/// Ok(res) => println!("Success: {:?}", res),
119/// }
120/// # }
121/// ```
122#[derive(Clone)]
123pub struct PostmasterTools<C> {
124 pub client: common::Client<C>,
125 pub auth: Box<dyn common::GetToken>,
126 _user_agent: String,
127 _base_url: String,
128 _root_url: String,
129}
130
131impl<C> common::Hub for PostmasterTools<C> {}
132
133impl<'a, C> PostmasterTools<C> {
134 pub fn new<A: 'static + common::GetToken>(
135 client: common::Client<C>,
136 auth: A,
137 ) -> PostmasterTools<C> {
138 PostmasterTools {
139 client,
140 auth: Box::new(auth),
141 _user_agent: "google-api-rust-client/7.0.0".to_string(),
142 _base_url: "https://gmailpostmastertools.googleapis.com/".to_string(),
143 _root_url: "https://gmailpostmastertools.googleapis.com/".to_string(),
144 }
145 }
146
147 pub fn domains(&'a self) -> DomainMethods<'a, C> {
148 DomainMethods { hub: self }
149 }
150
151 /// Set the user-agent header field to use in all requests to the server.
152 /// It defaults to `google-api-rust-client/7.0.0`.
153 ///
154 /// Returns the previously set user-agent.
155 pub fn user_agent(&mut self, agent_name: String) -> String {
156 std::mem::replace(&mut self._user_agent, agent_name)
157 }
158
159 /// Set the base url to use in all requests to the server.
160 /// It defaults to `https://gmailpostmastertools.googleapis.com/`.
161 ///
162 /// Returns the previously set base url.
163 pub fn base_url(&mut self, new_base_url: String) -> String {
164 std::mem::replace(&mut self._base_url, new_base_url)
165 }
166
167 /// Set the root url to use in all requests to the server.
168 /// It defaults to `https://gmailpostmastertools.googleapis.com/`.
169 ///
170 /// Returns the previously set root url.
171 pub fn root_url(&mut self, new_root_url: String) -> String {
172 std::mem::replace(&mut self._root_url, new_root_url)
173 }
174}
175
176// ############
177// SCHEMAS ###
178// ##########
179/// Metric on a particular delivery error type.
180///
181/// This type is not used in any activity, and only used as *part* of another schema.
182///
183#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
184#[serde_with::serde_as]
185#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
186pub struct DeliveryError {
187 /// The class of delivery error.
188 #[serde(rename = "errorClass")]
189 pub error_class: Option<String>,
190 /// The ratio of messages where the error occurred vs all authenticated traffic.
191 #[serde(rename = "errorRatio")]
192 pub error_ratio: Option<f64>,
193 /// The type of delivery error.
194 #[serde(rename = "errorType")]
195 pub error_type: Option<String>,
196}
197
198impl common::Part for DeliveryError {}
199
200/// A registered domain resource in the Postmaster API.
201///
202/// # Activities
203///
204/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
205/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
206///
207/// * [traffic stats get domains](DomainTrafficStatGetCall) (none)
208/// * [traffic stats list domains](DomainTrafficStatListCall) (none)
209/// * [get domains](DomainGetCall) (response)
210/// * [list domains](DomainListCall) (none)
211#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
212#[serde_with::serde_as]
213#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
214pub struct Domain {
215 /// Timestamp when the user registered this domain. Assigned by the server.
216 #[serde(rename = "createTime")]
217 pub create_time: Option<chrono::DateTime<chrono::offset::Utc>>,
218 /// The resource name of the Domain. Domain names have the form `domains/{domain_name}`, where domain_name is the fully qualified domain name (i.e., mymail.mydomain.com).
219 pub name: Option<String>,
220 /// User’s permission for this domain. Assigned by the server.
221 pub permission: Option<String>,
222}
223
224impl common::Resource for Domain {}
225impl common::ResponseResult for Domain {}
226
227/// [Feedback loop](https://support.google.com/mail/answer/6254652) identifier information.
228///
229/// This type is not used in any activity, and only used as *part* of another schema.
230///
231#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
232#[serde_with::serde_as]
233#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
234pub struct FeedbackLoop {
235 /// Feedback loop identifier that uniquely identifies individual campaigns.
236 pub id: Option<String>,
237 /// The ratio of user marked spam messages with the identifier vs the total number of inboxed messages with that identifier.
238 #[serde(rename = "spamRatio")]
239 pub spam_ratio: Option<f64>,
240}
241
242impl common::Part for FeedbackLoop {}
243
244/// IP Reputation information for a set of IPs in a specific reputation category.
245///
246/// This type is not used in any activity, and only used as *part* of another schema.
247///
248#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
249#[serde_with::serde_as]
250#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
251pub struct IpReputation {
252 /// Total number of unique IPs in this reputation category. This metric only pertains to traffic that passed [SPF](http://www.openspf.org/) or [DKIM](http://www.dkim.org/).
253 #[serde(rename = "ipCount")]
254 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
255 pub ip_count: Option<i64>,
256 /// The reputation category this IP reputation represents.
257 pub reputation: Option<String>,
258 /// A sample of IPs in this reputation category.
259 #[serde(rename = "sampleIps")]
260 pub sample_ips: Option<Vec<String>>,
261}
262
263impl common::Part for IpReputation {}
264
265/// Response message for ListDomains.
266///
267/// # Activities
268///
269/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
270/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
271///
272/// * [list domains](DomainListCall) (response)
273#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
274#[serde_with::serde_as]
275#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
276pub struct ListDomainsResponse {
277 /// The list of domains.
278 pub domains: Option<Vec<Domain>>,
279 /// Token to retrieve the next page of results, or empty if there are no more results in the list.
280 #[serde(rename = "nextPageToken")]
281 pub next_page_token: Option<String>,
282}
283
284impl common::ResponseResult for ListDomainsResponse {}
285
286/// Response message for ListTrafficStats.
287///
288/// # Activities
289///
290/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
291/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
292///
293/// * [traffic stats list domains](DomainTrafficStatListCall) (response)
294#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
295#[serde_with::serde_as]
296#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
297pub struct ListTrafficStatsResponse {
298 /// Token to retrieve the next page of results, or empty if there are no more results in the list.
299 #[serde(rename = "nextPageToken")]
300 pub next_page_token: Option<String>,
301 /// The list of TrafficStats.
302 #[serde(rename = "trafficStats")]
303 pub traffic_stats: Option<Vec<TrafficStats>>,
304}
305
306impl common::ResponseResult for ListTrafficStatsResponse {}
307
308/// Email traffic statistics pertaining to a specific date.
309///
310/// # Activities
311///
312/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
313/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
314///
315/// * [traffic stats get domains](DomainTrafficStatGetCall) (response)
316#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
317#[serde_with::serde_as]
318#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
319pub struct TrafficStats {
320 /// Delivery errors for the domain. This metric only pertains to traffic that passed [SPF](http://www.openspf.org/) or [DKIM](http://www.dkim.org/).
321 #[serde(rename = "deliveryErrors")]
322 pub delivery_errors: Option<Vec<DeliveryError>>,
323 /// The ratio of mail that successfully authenticated with DKIM vs. all mail that attempted to authenticate with [DKIM](http://www.dkim.org/). Spoofed mail is excluded.
324 #[serde(rename = "dkimSuccessRatio")]
325 pub dkim_success_ratio: Option<f64>,
326 /// The ratio of mail that passed [DMARC](https://dmarc.org/) alignment checks vs all mail received from the domain that successfully authenticated with either of [SPF](http://www.openspf.org/) or [DKIM](http://www.dkim.org/).
327 #[serde(rename = "dmarcSuccessRatio")]
328 pub dmarc_success_ratio: Option<f64>,
329 /// Reputation of the domain.
330 #[serde(rename = "domainReputation")]
331 pub domain_reputation: Option<String>,
332 /// The ratio of incoming mail (to Gmail), that passed secure transport (TLS) vs all mail received from that domain. This metric only pertains to traffic that passed [SPF](http://www.openspf.org/) or [DKIM](http://www.dkim.org/).
333 #[serde(rename = "inboundEncryptionRatio")]
334 pub inbound_encryption_ratio: Option<f64>,
335 /// Reputation information pertaining to the IP addresses of the email servers for the domain. There is exactly one entry for each reputation category except REPUTATION_CATEGORY_UNSPECIFIED.
336 #[serde(rename = "ipReputations")]
337 pub ip_reputations: Option<Vec<IpReputation>>,
338 /// The resource name of the traffic statistics. Traffic statistic names have the form `domains/{domain}/trafficStats/{date}`, where domain_name is the fully qualified domain name (i.e., mymail.mydomain.com) of the domain this traffic statistics pertains to and date is the date in yyyymmdd format that these statistics corresponds to. For example: domains/mymail.mydomain.com/trafficStats/20160807
339 pub name: Option<String>,
340 /// The ratio of outgoing mail (from Gmail) that was accepted over secure transport (TLS).
341 #[serde(rename = "outboundEncryptionRatio")]
342 pub outbound_encryption_ratio: Option<f64>,
343 /// Spammy [Feedback loop identifiers] (https://support.google.com/mail/answer/6254652) with their individual spam rates. This metric only pertains to traffic that is authenticated by [DKIM](http://www.dkim.org/).
344 #[serde(rename = "spammyFeedbackLoops")]
345 pub spammy_feedback_loops: Option<Vec<FeedbackLoop>>,
346 /// The ratio of mail that successfully authenticated with SPF vs. all mail that attempted to authenticate with [SPF](http://www.openspf.org/). Spoofed mail is excluded.
347 #[serde(rename = "spfSuccessRatio")]
348 pub spf_success_ratio: Option<f64>,
349 /// The ratio of user-report spam vs. email that was sent to the inbox. This is potentially inexact -- users may want to refer to the description of the interval fields userReportedSpamRatioLowerBound and userReportedSpamRatioUpperBound for more explicit accuracy guarantees. This metric only pertains to emails authenticated by [DKIM](http://www.dkim.org/).
350 #[serde(rename = "userReportedSpamRatio")]
351 pub user_reported_spam_ratio: Option<f64>,
352 /// The lower bound of the confidence interval for the user reported spam ratio. If this field is set, then the value of userReportedSpamRatio is set to the midpoint of this interval and is thus inexact. However, the true ratio is guaranteed to be in between this lower bound and the corresponding upper bound 95% of the time. This metric only pertains to emails authenticated by [DKIM](http://www.dkim.org/).
353 #[serde(rename = "userReportedSpamRatioLowerBound")]
354 pub user_reported_spam_ratio_lower_bound: Option<f64>,
355 /// The upper bound of the confidence interval for the user reported spam ratio. If this field is set, then the value of userReportedSpamRatio is set to the midpoint of this interval and is thus inexact. However, the true ratio is guaranteed to be in between this upper bound and the corresponding lower bound 95% of the time. This metric only pertains to emails authenticated by [DKIM](http://www.dkim.org/).
356 #[serde(rename = "userReportedSpamRatioUpperBound")]
357 pub user_reported_spam_ratio_upper_bound: Option<f64>,
358}
359
360impl common::ResponseResult for TrafficStats {}
361
362// ###################
363// MethodBuilders ###
364// #################
365
366/// A builder providing access to all methods supported on *domain* resources.
367/// It is not used directly, but through the [`PostmasterTools`] hub.
368///
369/// # Example
370///
371/// Instantiate a resource builder
372///
373/// ```test_harness,no_run
374/// extern crate hyper;
375/// extern crate hyper_rustls;
376/// extern crate google_gmailpostmastertools1 as gmailpostmastertools1;
377///
378/// # async fn dox() {
379/// use gmailpostmastertools1::{PostmasterTools, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
380///
381/// let secret: yup_oauth2::ApplicationSecret = Default::default();
382/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
383/// .with_native_roots()
384/// .unwrap()
385/// .https_only()
386/// .enable_http2()
387/// .build();
388///
389/// let executor = hyper_util::rt::TokioExecutor::new();
390/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
391/// secret,
392/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
393/// yup_oauth2::client::CustomHyperClientBuilder::from(
394/// hyper_util::client::legacy::Client::builder(executor).build(connector),
395/// ),
396/// ).build().await.unwrap();
397///
398/// let client = hyper_util::client::legacy::Client::builder(
399/// hyper_util::rt::TokioExecutor::new()
400/// )
401/// .build(
402/// hyper_rustls::HttpsConnectorBuilder::new()
403/// .with_native_roots()
404/// .unwrap()
405/// .https_or_http()
406/// .enable_http2()
407/// .build()
408/// );
409/// let mut hub = PostmasterTools::new(client, auth);
410/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
411/// // like `get(...)`, `list(...)`, `traffic_stats_get(...)` and `traffic_stats_list(...)`
412/// // to build up your call.
413/// let rb = hub.domains();
414/// # }
415/// ```
416pub struct DomainMethods<'a, C>
417where
418 C: 'a,
419{
420 hub: &'a PostmasterTools<C>,
421}
422
423impl<'a, C> common::MethodsBuilder for DomainMethods<'a, C> {}
424
425impl<'a, C> DomainMethods<'a, C> {
426 /// Create a builder to help you perform the following task:
427 ///
428 /// Get traffic statistics for a domain on a specific date. Returns PERMISSION_DENIED if user does not have permission to access TrafficStats for the domain.
429 ///
430 /// # Arguments
431 ///
432 /// * `name` - The resource name of the traffic statistics to get. E.g., domains/mymail.mydomain.com/trafficStats/20160807.
433 pub fn traffic_stats_get(&self, name: &str) -> DomainTrafficStatGetCall<'a, C> {
434 DomainTrafficStatGetCall {
435 hub: self.hub,
436 _name: name.to_string(),
437 _delegate: Default::default(),
438 _additional_params: Default::default(),
439 _scopes: Default::default(),
440 }
441 }
442
443 /// Create a builder to help you perform the following task:
444 ///
445 /// List traffic statistics for all available days. Returns PERMISSION_DENIED if user does not have permission to access TrafficStats for the domain.
446 ///
447 /// # Arguments
448 ///
449 /// * `parent` - The resource name of the domain whose traffic statistics we'd like to list. It should have the form `domains/{domain_name}`, where domain_name is the fully qualified domain name.
450 pub fn traffic_stats_list(&self, parent: &str) -> DomainTrafficStatListCall<'a, C> {
451 DomainTrafficStatListCall {
452 hub: self.hub,
453 _parent: parent.to_string(),
454 _start_date_year: Default::default(),
455 _start_date_month: Default::default(),
456 _start_date_day: Default::default(),
457 _page_token: Default::default(),
458 _page_size: Default::default(),
459 _end_date_year: Default::default(),
460 _end_date_month: Default::default(),
461 _end_date_day: Default::default(),
462 _delegate: Default::default(),
463 _additional_params: Default::default(),
464 _scopes: Default::default(),
465 }
466 }
467
468 /// Create a builder to help you perform the following task:
469 ///
470 /// Gets a specific domain registered by the client. Returns NOT_FOUND if the domain does not exist.
471 ///
472 /// # Arguments
473 ///
474 /// * `name` - The resource name of the domain. It should have the form `domains/{domain_name}`, where domain_name is the fully qualified domain name.
475 pub fn get(&self, name: &str) -> DomainGetCall<'a, C> {
476 DomainGetCall {
477 hub: self.hub,
478 _name: name.to_string(),
479 _delegate: Default::default(),
480 _additional_params: Default::default(),
481 _scopes: Default::default(),
482 }
483 }
484
485 /// Create a builder to help you perform the following task:
486 ///
487 /// Lists the domains that have been registered by the client. The order of domains in the response is unspecified and non-deterministic. Newly created domains will not necessarily be added to the end of this list.
488 pub fn list(&self) -> DomainListCall<'a, C> {
489 DomainListCall {
490 hub: self.hub,
491 _page_token: Default::default(),
492 _page_size: Default::default(),
493 _delegate: Default::default(),
494 _additional_params: Default::default(),
495 _scopes: Default::default(),
496 }
497 }
498}
499
500// ###################
501// CallBuilders ###
502// #################
503
504/// Get traffic statistics for a domain on a specific date. Returns PERMISSION_DENIED if user does not have permission to access TrafficStats for the domain.
505///
506/// A builder for the *trafficStats.get* method supported by a *domain* resource.
507/// It is not used directly, but through a [`DomainMethods`] instance.
508///
509/// # Example
510///
511/// Instantiate a resource method builder
512///
513/// ```test_harness,no_run
514/// # extern crate hyper;
515/// # extern crate hyper_rustls;
516/// # extern crate google_gmailpostmastertools1 as gmailpostmastertools1;
517/// # async fn dox() {
518/// # use gmailpostmastertools1::{PostmasterTools, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
519///
520/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
521/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
522/// # .with_native_roots()
523/// # .unwrap()
524/// # .https_only()
525/// # .enable_http2()
526/// # .build();
527///
528/// # let executor = hyper_util::rt::TokioExecutor::new();
529/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
530/// # secret,
531/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
532/// # yup_oauth2::client::CustomHyperClientBuilder::from(
533/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
534/// # ),
535/// # ).build().await.unwrap();
536///
537/// # let client = hyper_util::client::legacy::Client::builder(
538/// # hyper_util::rt::TokioExecutor::new()
539/// # )
540/// # .build(
541/// # hyper_rustls::HttpsConnectorBuilder::new()
542/// # .with_native_roots()
543/// # .unwrap()
544/// # .https_or_http()
545/// # .enable_http2()
546/// # .build()
547/// # );
548/// # let mut hub = PostmasterTools::new(client, auth);
549/// // You can configure optional parameters by calling the respective setters at will, and
550/// // execute the final call using `doit()`.
551/// // Values shown here are possibly random and not representative !
552/// let result = hub.domains().traffic_stats_get("name")
553/// .doit().await;
554/// # }
555/// ```
556pub struct DomainTrafficStatGetCall<'a, C>
557where
558 C: 'a,
559{
560 hub: &'a PostmasterTools<C>,
561 _name: String,
562 _delegate: Option<&'a mut dyn common::Delegate>,
563 _additional_params: HashMap<String, String>,
564 _scopes: BTreeSet<String>,
565}
566
567impl<'a, C> common::CallBuilder for DomainTrafficStatGetCall<'a, C> {}
568
569impl<'a, C> DomainTrafficStatGetCall<'a, C>
570where
571 C: common::Connector,
572{
573 /// Perform the operation you have build so far.
574 pub async fn doit(mut self) -> common::Result<(common::Response, TrafficStats)> {
575 use std::borrow::Cow;
576 use std::io::{Read, Seek};
577
578 use common::{url::Params, ToParts};
579 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
580
581 let mut dd = common::DefaultDelegate;
582 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
583 dlg.begin(common::MethodInfo {
584 id: "gmailpostmastertools.domains.trafficStats.get",
585 http_method: hyper::Method::GET,
586 });
587
588 for &field in ["alt", "name"].iter() {
589 if self._additional_params.contains_key(field) {
590 dlg.finished(false);
591 return Err(common::Error::FieldClash(field));
592 }
593 }
594
595 let mut params = Params::with_capacity(3 + self._additional_params.len());
596 params.push("name", self._name);
597
598 params.extend(self._additional_params.iter());
599
600 params.push("alt", "json");
601 let mut url = self.hub._base_url.clone() + "v1/{+name}";
602 if self._scopes.is_empty() {
603 self._scopes
604 .insert(Scope::PostmasterReadonly.as_ref().to_string());
605 }
606
607 #[allow(clippy::single_element_loop)]
608 for &(find_this, param_name) in [("{+name}", "name")].iter() {
609 url = params.uri_replacement(url, param_name, find_this, true);
610 }
611 {
612 let to_remove = ["name"];
613 params.remove_params(&to_remove);
614 }
615
616 let url = params.parse_with_url(&url);
617
618 loop {
619 let token = match self
620 .hub
621 .auth
622 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
623 .await
624 {
625 Ok(token) => token,
626 Err(e) => match dlg.token(e) {
627 Ok(token) => token,
628 Err(e) => {
629 dlg.finished(false);
630 return Err(common::Error::MissingToken(e));
631 }
632 },
633 };
634 let mut req_result = {
635 let client = &self.hub.client;
636 dlg.pre_request();
637 let mut req_builder = hyper::Request::builder()
638 .method(hyper::Method::GET)
639 .uri(url.as_str())
640 .header(USER_AGENT, self.hub._user_agent.clone());
641
642 if let Some(token) = token.as_ref() {
643 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
644 }
645
646 let request = req_builder
647 .header(CONTENT_LENGTH, 0_u64)
648 .body(common::to_body::<String>(None));
649
650 client.request(request.unwrap()).await
651 };
652
653 match req_result {
654 Err(err) => {
655 if let common::Retry::After(d) = dlg.http_error(&err) {
656 sleep(d).await;
657 continue;
658 }
659 dlg.finished(false);
660 return Err(common::Error::HttpError(err));
661 }
662 Ok(res) => {
663 let (mut parts, body) = res.into_parts();
664 let mut body = common::Body::new(body);
665 if !parts.status.is_success() {
666 let bytes = common::to_bytes(body).await.unwrap_or_default();
667 let error = serde_json::from_str(&common::to_string(&bytes));
668 let response = common::to_response(parts, bytes.into());
669
670 if let common::Retry::After(d) =
671 dlg.http_failure(&response, error.as_ref().ok())
672 {
673 sleep(d).await;
674 continue;
675 }
676
677 dlg.finished(false);
678
679 return Err(match error {
680 Ok(value) => common::Error::BadRequest(value),
681 _ => common::Error::Failure(response),
682 });
683 }
684 let response = {
685 let bytes = common::to_bytes(body).await.unwrap_or_default();
686 let encoded = common::to_string(&bytes);
687 match serde_json::from_str(&encoded) {
688 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
689 Err(error) => {
690 dlg.response_json_decode_error(&encoded, &error);
691 return Err(common::Error::JsonDecodeError(
692 encoded.to_string(),
693 error,
694 ));
695 }
696 }
697 };
698
699 dlg.finished(true);
700 return Ok(response);
701 }
702 }
703 }
704 }
705
706 /// The resource name of the traffic statistics to get. E.g., domains/mymail.mydomain.com/trafficStats/20160807.
707 ///
708 /// Sets the *name* path property to the given value.
709 ///
710 /// Even though the property as already been set when instantiating this call,
711 /// we provide this method for API completeness.
712 pub fn name(mut self, new_value: &str) -> DomainTrafficStatGetCall<'a, C> {
713 self._name = new_value.to_string();
714 self
715 }
716 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
717 /// while executing the actual API request.
718 ///
719 /// ````text
720 /// It should be used to handle progress information, and to implement a certain level of resilience.
721 /// ````
722 ///
723 /// Sets the *delegate* property to the given value.
724 pub fn delegate(
725 mut self,
726 new_value: &'a mut dyn common::Delegate,
727 ) -> DomainTrafficStatGetCall<'a, C> {
728 self._delegate = Some(new_value);
729 self
730 }
731
732 /// Set any additional parameter of the query string used in the request.
733 /// It should be used to set parameters which are not yet available through their own
734 /// setters.
735 ///
736 /// Please note that this method must not be used to set any of the known parameters
737 /// which have their own setter method. If done anyway, the request will fail.
738 ///
739 /// # Additional Parameters
740 ///
741 /// * *$.xgafv* (query-string) - V1 error format.
742 /// * *access_token* (query-string) - OAuth access token.
743 /// * *alt* (query-string) - Data format for response.
744 /// * *callback* (query-string) - JSONP
745 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
746 /// * *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.
747 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
748 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
749 /// * *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.
750 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
751 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
752 pub fn param<T>(mut self, name: T, value: T) -> DomainTrafficStatGetCall<'a, C>
753 where
754 T: AsRef<str>,
755 {
756 self._additional_params
757 .insert(name.as_ref().to_string(), value.as_ref().to_string());
758 self
759 }
760
761 /// Identifies the authorization scope for the method you are building.
762 ///
763 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
764 /// [`Scope::PostmasterReadonly`].
765 ///
766 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
767 /// tokens for more than one scope.
768 ///
769 /// Usually there is more than one suitable scope to authorize an operation, some of which may
770 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
771 /// sufficient, a read-write scope will do as well.
772 pub fn add_scope<St>(mut self, scope: St) -> DomainTrafficStatGetCall<'a, C>
773 where
774 St: AsRef<str>,
775 {
776 self._scopes.insert(String::from(scope.as_ref()));
777 self
778 }
779 /// Identifies the authorization scope(s) for the method you are building.
780 ///
781 /// See [`Self::add_scope()`] for details.
782 pub fn add_scopes<I, St>(mut self, scopes: I) -> DomainTrafficStatGetCall<'a, C>
783 where
784 I: IntoIterator<Item = St>,
785 St: AsRef<str>,
786 {
787 self._scopes
788 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
789 self
790 }
791
792 /// Removes all scopes, and no default scope will be used either.
793 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
794 /// for details).
795 pub fn clear_scopes(mut self) -> DomainTrafficStatGetCall<'a, C> {
796 self._scopes.clear();
797 self
798 }
799}
800
801/// List traffic statistics for all available days. Returns PERMISSION_DENIED if user does not have permission to access TrafficStats for the domain.
802///
803/// A builder for the *trafficStats.list* method supported by a *domain* resource.
804/// It is not used directly, but through a [`DomainMethods`] instance.
805///
806/// # Example
807///
808/// Instantiate a resource method builder
809///
810/// ```test_harness,no_run
811/// # extern crate hyper;
812/// # extern crate hyper_rustls;
813/// # extern crate google_gmailpostmastertools1 as gmailpostmastertools1;
814/// # async fn dox() {
815/// # use gmailpostmastertools1::{PostmasterTools, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
816///
817/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
818/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
819/// # .with_native_roots()
820/// # .unwrap()
821/// # .https_only()
822/// # .enable_http2()
823/// # .build();
824///
825/// # let executor = hyper_util::rt::TokioExecutor::new();
826/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
827/// # secret,
828/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
829/// # yup_oauth2::client::CustomHyperClientBuilder::from(
830/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
831/// # ),
832/// # ).build().await.unwrap();
833///
834/// # let client = hyper_util::client::legacy::Client::builder(
835/// # hyper_util::rt::TokioExecutor::new()
836/// # )
837/// # .build(
838/// # hyper_rustls::HttpsConnectorBuilder::new()
839/// # .with_native_roots()
840/// # .unwrap()
841/// # .https_or_http()
842/// # .enable_http2()
843/// # .build()
844/// # );
845/// # let mut hub = PostmasterTools::new(client, auth);
846/// // You can configure optional parameters by calling the respective setters at will, and
847/// // execute the final call using `doit()`.
848/// // Values shown here are possibly random and not representative !
849/// let result = hub.domains().traffic_stats_list("parent")
850/// .start_date_year(-50)
851/// .start_date_month(-50)
852/// .start_date_day(-7)
853/// .page_token("gubergren")
854/// .page_size(-17)
855/// .end_date_year(-99)
856/// .end_date_month(-56)
857/// .end_date_day(-25)
858/// .doit().await;
859/// # }
860/// ```
861pub struct DomainTrafficStatListCall<'a, C>
862where
863 C: 'a,
864{
865 hub: &'a PostmasterTools<C>,
866 _parent: String,
867 _start_date_year: Option<i32>,
868 _start_date_month: Option<i32>,
869 _start_date_day: Option<i32>,
870 _page_token: Option<String>,
871 _page_size: Option<i32>,
872 _end_date_year: Option<i32>,
873 _end_date_month: Option<i32>,
874 _end_date_day: Option<i32>,
875 _delegate: Option<&'a mut dyn common::Delegate>,
876 _additional_params: HashMap<String, String>,
877 _scopes: BTreeSet<String>,
878}
879
880impl<'a, C> common::CallBuilder for DomainTrafficStatListCall<'a, C> {}
881
882impl<'a, C> DomainTrafficStatListCall<'a, C>
883where
884 C: common::Connector,
885{
886 /// Perform the operation you have build so far.
887 pub async fn doit(mut self) -> common::Result<(common::Response, ListTrafficStatsResponse)> {
888 use std::borrow::Cow;
889 use std::io::{Read, Seek};
890
891 use common::{url::Params, ToParts};
892 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
893
894 let mut dd = common::DefaultDelegate;
895 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
896 dlg.begin(common::MethodInfo {
897 id: "gmailpostmastertools.domains.trafficStats.list",
898 http_method: hyper::Method::GET,
899 });
900
901 for &field in [
902 "alt",
903 "parent",
904 "startDate.year",
905 "startDate.month",
906 "startDate.day",
907 "pageToken",
908 "pageSize",
909 "endDate.year",
910 "endDate.month",
911 "endDate.day",
912 ]
913 .iter()
914 {
915 if self._additional_params.contains_key(field) {
916 dlg.finished(false);
917 return Err(common::Error::FieldClash(field));
918 }
919 }
920
921 let mut params = Params::with_capacity(11 + self._additional_params.len());
922 params.push("parent", self._parent);
923 if let Some(value) = self._start_date_year.as_ref() {
924 params.push("startDate.year", value.to_string());
925 }
926 if let Some(value) = self._start_date_month.as_ref() {
927 params.push("startDate.month", value.to_string());
928 }
929 if let Some(value) = self._start_date_day.as_ref() {
930 params.push("startDate.day", value.to_string());
931 }
932 if let Some(value) = self._page_token.as_ref() {
933 params.push("pageToken", value);
934 }
935 if let Some(value) = self._page_size.as_ref() {
936 params.push("pageSize", value.to_string());
937 }
938 if let Some(value) = self._end_date_year.as_ref() {
939 params.push("endDate.year", value.to_string());
940 }
941 if let Some(value) = self._end_date_month.as_ref() {
942 params.push("endDate.month", value.to_string());
943 }
944 if let Some(value) = self._end_date_day.as_ref() {
945 params.push("endDate.day", value.to_string());
946 }
947
948 params.extend(self._additional_params.iter());
949
950 params.push("alt", "json");
951 let mut url = self.hub._base_url.clone() + "v1/{+parent}/trafficStats";
952 if self._scopes.is_empty() {
953 self._scopes
954 .insert(Scope::PostmasterReadonly.as_ref().to_string());
955 }
956
957 #[allow(clippy::single_element_loop)]
958 for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
959 url = params.uri_replacement(url, param_name, find_this, true);
960 }
961 {
962 let to_remove = ["parent"];
963 params.remove_params(&to_remove);
964 }
965
966 let url = params.parse_with_url(&url);
967
968 loop {
969 let token = match self
970 .hub
971 .auth
972 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
973 .await
974 {
975 Ok(token) => token,
976 Err(e) => match dlg.token(e) {
977 Ok(token) => token,
978 Err(e) => {
979 dlg.finished(false);
980 return Err(common::Error::MissingToken(e));
981 }
982 },
983 };
984 let mut req_result = {
985 let client = &self.hub.client;
986 dlg.pre_request();
987 let mut req_builder = hyper::Request::builder()
988 .method(hyper::Method::GET)
989 .uri(url.as_str())
990 .header(USER_AGENT, self.hub._user_agent.clone());
991
992 if let Some(token) = token.as_ref() {
993 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
994 }
995
996 let request = req_builder
997 .header(CONTENT_LENGTH, 0_u64)
998 .body(common::to_body::<String>(None));
999
1000 client.request(request.unwrap()).await
1001 };
1002
1003 match req_result {
1004 Err(err) => {
1005 if let common::Retry::After(d) = dlg.http_error(&err) {
1006 sleep(d).await;
1007 continue;
1008 }
1009 dlg.finished(false);
1010 return Err(common::Error::HttpError(err));
1011 }
1012 Ok(res) => {
1013 let (mut parts, body) = res.into_parts();
1014 let mut body = common::Body::new(body);
1015 if !parts.status.is_success() {
1016 let bytes = common::to_bytes(body).await.unwrap_or_default();
1017 let error = serde_json::from_str(&common::to_string(&bytes));
1018 let response = common::to_response(parts, bytes.into());
1019
1020 if let common::Retry::After(d) =
1021 dlg.http_failure(&response, error.as_ref().ok())
1022 {
1023 sleep(d).await;
1024 continue;
1025 }
1026
1027 dlg.finished(false);
1028
1029 return Err(match error {
1030 Ok(value) => common::Error::BadRequest(value),
1031 _ => common::Error::Failure(response),
1032 });
1033 }
1034 let response = {
1035 let bytes = common::to_bytes(body).await.unwrap_or_default();
1036 let encoded = common::to_string(&bytes);
1037 match serde_json::from_str(&encoded) {
1038 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1039 Err(error) => {
1040 dlg.response_json_decode_error(&encoded, &error);
1041 return Err(common::Error::JsonDecodeError(
1042 encoded.to_string(),
1043 error,
1044 ));
1045 }
1046 }
1047 };
1048
1049 dlg.finished(true);
1050 return Ok(response);
1051 }
1052 }
1053 }
1054 }
1055
1056 /// The resource name of the domain whose traffic statistics we'd like to list. It should have the form `domains/{domain_name}`, where domain_name is the fully qualified domain name.
1057 ///
1058 /// Sets the *parent* path property to the given value.
1059 ///
1060 /// Even though the property as already been set when instantiating this call,
1061 /// we provide this method for API completeness.
1062 pub fn parent(mut self, new_value: &str) -> DomainTrafficStatListCall<'a, C> {
1063 self._parent = new_value.to_string();
1064 self
1065 }
1066 /// Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year.
1067 ///
1068 /// Sets the *start date.year* query property to the given value.
1069 pub fn start_date_year(mut self, new_value: i32) -> DomainTrafficStatListCall<'a, C> {
1070 self._start_date_year = Some(new_value);
1071 self
1072 }
1073 /// Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day.
1074 ///
1075 /// Sets the *start date.month* query property to the given value.
1076 pub fn start_date_month(mut self, new_value: i32) -> DomainTrafficStatListCall<'a, C> {
1077 self._start_date_month = Some(new_value);
1078 self
1079 }
1080 /// Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant.
1081 ///
1082 /// Sets the *start date.day* query property to the given value.
1083 pub fn start_date_day(mut self, new_value: i32) -> DomainTrafficStatListCall<'a, C> {
1084 self._start_date_day = Some(new_value);
1085 self
1086 }
1087 /// The next_page_token value returned from a previous List request, if any. This is the value of ListTrafficStatsResponse.next_page_token returned from the previous call to `ListTrafficStats` method.
1088 ///
1089 /// Sets the *page token* query property to the given value.
1090 pub fn page_token(mut self, new_value: &str) -> DomainTrafficStatListCall<'a, C> {
1091 self._page_token = Some(new_value.to_string());
1092 self
1093 }
1094 /// Requested page size. Server may return fewer TrafficStats than requested. If unspecified, server will pick an appropriate default.
1095 ///
1096 /// Sets the *page size* query property to the given value.
1097 pub fn page_size(mut self, new_value: i32) -> DomainTrafficStatListCall<'a, C> {
1098 self._page_size = Some(new_value);
1099 self
1100 }
1101 /// Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year.
1102 ///
1103 /// Sets the *end date.year* query property to the given value.
1104 pub fn end_date_year(mut self, new_value: i32) -> DomainTrafficStatListCall<'a, C> {
1105 self._end_date_year = Some(new_value);
1106 self
1107 }
1108 /// Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day.
1109 ///
1110 /// Sets the *end date.month* query property to the given value.
1111 pub fn end_date_month(mut self, new_value: i32) -> DomainTrafficStatListCall<'a, C> {
1112 self._end_date_month = Some(new_value);
1113 self
1114 }
1115 /// Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant.
1116 ///
1117 /// Sets the *end date.day* query property to the given value.
1118 pub fn end_date_day(mut self, new_value: i32) -> DomainTrafficStatListCall<'a, C> {
1119 self._end_date_day = Some(new_value);
1120 self
1121 }
1122 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1123 /// while executing the actual API request.
1124 ///
1125 /// ````text
1126 /// It should be used to handle progress information, and to implement a certain level of resilience.
1127 /// ````
1128 ///
1129 /// Sets the *delegate* property to the given value.
1130 pub fn delegate(
1131 mut self,
1132 new_value: &'a mut dyn common::Delegate,
1133 ) -> DomainTrafficStatListCall<'a, C> {
1134 self._delegate = Some(new_value);
1135 self
1136 }
1137
1138 /// Set any additional parameter of the query string used in the request.
1139 /// It should be used to set parameters which are not yet available through their own
1140 /// setters.
1141 ///
1142 /// Please note that this method must not be used to set any of the known parameters
1143 /// which have their own setter method. If done anyway, the request will fail.
1144 ///
1145 /// # Additional Parameters
1146 ///
1147 /// * *$.xgafv* (query-string) - V1 error format.
1148 /// * *access_token* (query-string) - OAuth access token.
1149 /// * *alt* (query-string) - Data format for response.
1150 /// * *callback* (query-string) - JSONP
1151 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1152 /// * *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.
1153 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1154 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1155 /// * *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.
1156 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1157 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1158 pub fn param<T>(mut self, name: T, value: T) -> DomainTrafficStatListCall<'a, C>
1159 where
1160 T: AsRef<str>,
1161 {
1162 self._additional_params
1163 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1164 self
1165 }
1166
1167 /// Identifies the authorization scope for the method you are building.
1168 ///
1169 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1170 /// [`Scope::PostmasterReadonly`].
1171 ///
1172 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1173 /// tokens for more than one scope.
1174 ///
1175 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1176 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1177 /// sufficient, a read-write scope will do as well.
1178 pub fn add_scope<St>(mut self, scope: St) -> DomainTrafficStatListCall<'a, C>
1179 where
1180 St: AsRef<str>,
1181 {
1182 self._scopes.insert(String::from(scope.as_ref()));
1183 self
1184 }
1185 /// Identifies the authorization scope(s) for the method you are building.
1186 ///
1187 /// See [`Self::add_scope()`] for details.
1188 pub fn add_scopes<I, St>(mut self, scopes: I) -> DomainTrafficStatListCall<'a, C>
1189 where
1190 I: IntoIterator<Item = St>,
1191 St: AsRef<str>,
1192 {
1193 self._scopes
1194 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1195 self
1196 }
1197
1198 /// Removes all scopes, and no default scope will be used either.
1199 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1200 /// for details).
1201 pub fn clear_scopes(mut self) -> DomainTrafficStatListCall<'a, C> {
1202 self._scopes.clear();
1203 self
1204 }
1205}
1206
1207/// Gets a specific domain registered by the client. Returns NOT_FOUND if the domain does not exist.
1208///
1209/// A builder for the *get* method supported by a *domain* resource.
1210/// It is not used directly, but through a [`DomainMethods`] instance.
1211///
1212/// # Example
1213///
1214/// Instantiate a resource method builder
1215///
1216/// ```test_harness,no_run
1217/// # extern crate hyper;
1218/// # extern crate hyper_rustls;
1219/// # extern crate google_gmailpostmastertools1 as gmailpostmastertools1;
1220/// # async fn dox() {
1221/// # use gmailpostmastertools1::{PostmasterTools, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1222///
1223/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1224/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1225/// # .with_native_roots()
1226/// # .unwrap()
1227/// # .https_only()
1228/// # .enable_http2()
1229/// # .build();
1230///
1231/// # let executor = hyper_util::rt::TokioExecutor::new();
1232/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1233/// # secret,
1234/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1235/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1236/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1237/// # ),
1238/// # ).build().await.unwrap();
1239///
1240/// # let client = hyper_util::client::legacy::Client::builder(
1241/// # hyper_util::rt::TokioExecutor::new()
1242/// # )
1243/// # .build(
1244/// # hyper_rustls::HttpsConnectorBuilder::new()
1245/// # .with_native_roots()
1246/// # .unwrap()
1247/// # .https_or_http()
1248/// # .enable_http2()
1249/// # .build()
1250/// # );
1251/// # let mut hub = PostmasterTools::new(client, auth);
1252/// // You can configure optional parameters by calling the respective setters at will, and
1253/// // execute the final call using `doit()`.
1254/// // Values shown here are possibly random and not representative !
1255/// let result = hub.domains().get("name")
1256/// .doit().await;
1257/// # }
1258/// ```
1259pub struct DomainGetCall<'a, C>
1260where
1261 C: 'a,
1262{
1263 hub: &'a PostmasterTools<C>,
1264 _name: String,
1265 _delegate: Option<&'a mut dyn common::Delegate>,
1266 _additional_params: HashMap<String, String>,
1267 _scopes: BTreeSet<String>,
1268}
1269
1270impl<'a, C> common::CallBuilder for DomainGetCall<'a, C> {}
1271
1272impl<'a, C> DomainGetCall<'a, C>
1273where
1274 C: common::Connector,
1275{
1276 /// Perform the operation you have build so far.
1277 pub async fn doit(mut self) -> common::Result<(common::Response, Domain)> {
1278 use std::borrow::Cow;
1279 use std::io::{Read, Seek};
1280
1281 use common::{url::Params, ToParts};
1282 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1283
1284 let mut dd = common::DefaultDelegate;
1285 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1286 dlg.begin(common::MethodInfo {
1287 id: "gmailpostmastertools.domains.get",
1288 http_method: hyper::Method::GET,
1289 });
1290
1291 for &field in ["alt", "name"].iter() {
1292 if self._additional_params.contains_key(field) {
1293 dlg.finished(false);
1294 return Err(common::Error::FieldClash(field));
1295 }
1296 }
1297
1298 let mut params = Params::with_capacity(3 + self._additional_params.len());
1299 params.push("name", self._name);
1300
1301 params.extend(self._additional_params.iter());
1302
1303 params.push("alt", "json");
1304 let mut url = self.hub._base_url.clone() + "v1/{+name}";
1305 if self._scopes.is_empty() {
1306 self._scopes
1307 .insert(Scope::PostmasterReadonly.as_ref().to_string());
1308 }
1309
1310 #[allow(clippy::single_element_loop)]
1311 for &(find_this, param_name) in [("{+name}", "name")].iter() {
1312 url = params.uri_replacement(url, param_name, find_this, true);
1313 }
1314 {
1315 let to_remove = ["name"];
1316 params.remove_params(&to_remove);
1317 }
1318
1319 let url = params.parse_with_url(&url);
1320
1321 loop {
1322 let token = match self
1323 .hub
1324 .auth
1325 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1326 .await
1327 {
1328 Ok(token) => token,
1329 Err(e) => match dlg.token(e) {
1330 Ok(token) => token,
1331 Err(e) => {
1332 dlg.finished(false);
1333 return Err(common::Error::MissingToken(e));
1334 }
1335 },
1336 };
1337 let mut req_result = {
1338 let client = &self.hub.client;
1339 dlg.pre_request();
1340 let mut req_builder = hyper::Request::builder()
1341 .method(hyper::Method::GET)
1342 .uri(url.as_str())
1343 .header(USER_AGENT, self.hub._user_agent.clone());
1344
1345 if let Some(token) = token.as_ref() {
1346 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1347 }
1348
1349 let request = req_builder
1350 .header(CONTENT_LENGTH, 0_u64)
1351 .body(common::to_body::<String>(None));
1352
1353 client.request(request.unwrap()).await
1354 };
1355
1356 match req_result {
1357 Err(err) => {
1358 if let common::Retry::After(d) = dlg.http_error(&err) {
1359 sleep(d).await;
1360 continue;
1361 }
1362 dlg.finished(false);
1363 return Err(common::Error::HttpError(err));
1364 }
1365 Ok(res) => {
1366 let (mut parts, body) = res.into_parts();
1367 let mut body = common::Body::new(body);
1368 if !parts.status.is_success() {
1369 let bytes = common::to_bytes(body).await.unwrap_or_default();
1370 let error = serde_json::from_str(&common::to_string(&bytes));
1371 let response = common::to_response(parts, bytes.into());
1372
1373 if let common::Retry::After(d) =
1374 dlg.http_failure(&response, error.as_ref().ok())
1375 {
1376 sleep(d).await;
1377 continue;
1378 }
1379
1380 dlg.finished(false);
1381
1382 return Err(match error {
1383 Ok(value) => common::Error::BadRequest(value),
1384 _ => common::Error::Failure(response),
1385 });
1386 }
1387 let response = {
1388 let bytes = common::to_bytes(body).await.unwrap_or_default();
1389 let encoded = common::to_string(&bytes);
1390 match serde_json::from_str(&encoded) {
1391 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1392 Err(error) => {
1393 dlg.response_json_decode_error(&encoded, &error);
1394 return Err(common::Error::JsonDecodeError(
1395 encoded.to_string(),
1396 error,
1397 ));
1398 }
1399 }
1400 };
1401
1402 dlg.finished(true);
1403 return Ok(response);
1404 }
1405 }
1406 }
1407 }
1408
1409 /// The resource name of the domain. It should have the form `domains/{domain_name}`, where domain_name is the fully qualified domain name.
1410 ///
1411 /// Sets the *name* path property to the given value.
1412 ///
1413 /// Even though the property as already been set when instantiating this call,
1414 /// we provide this method for API completeness.
1415 pub fn name(mut self, new_value: &str) -> DomainGetCall<'a, C> {
1416 self._name = new_value.to_string();
1417 self
1418 }
1419 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1420 /// while executing the actual API request.
1421 ///
1422 /// ````text
1423 /// It should be used to handle progress information, and to implement a certain level of resilience.
1424 /// ````
1425 ///
1426 /// Sets the *delegate* property to the given value.
1427 pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> DomainGetCall<'a, C> {
1428 self._delegate = Some(new_value);
1429 self
1430 }
1431
1432 /// Set any additional parameter of the query string used in the request.
1433 /// It should be used to set parameters which are not yet available through their own
1434 /// setters.
1435 ///
1436 /// Please note that this method must not be used to set any of the known parameters
1437 /// which have their own setter method. If done anyway, the request will fail.
1438 ///
1439 /// # Additional Parameters
1440 ///
1441 /// * *$.xgafv* (query-string) - V1 error format.
1442 /// * *access_token* (query-string) - OAuth access token.
1443 /// * *alt* (query-string) - Data format for response.
1444 /// * *callback* (query-string) - JSONP
1445 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1446 /// * *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.
1447 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1448 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1449 /// * *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.
1450 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1451 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1452 pub fn param<T>(mut self, name: T, value: T) -> DomainGetCall<'a, C>
1453 where
1454 T: AsRef<str>,
1455 {
1456 self._additional_params
1457 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1458 self
1459 }
1460
1461 /// Identifies the authorization scope for the method you are building.
1462 ///
1463 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1464 /// [`Scope::PostmasterReadonly`].
1465 ///
1466 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1467 /// tokens for more than one scope.
1468 ///
1469 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1470 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1471 /// sufficient, a read-write scope will do as well.
1472 pub fn add_scope<St>(mut self, scope: St) -> DomainGetCall<'a, C>
1473 where
1474 St: AsRef<str>,
1475 {
1476 self._scopes.insert(String::from(scope.as_ref()));
1477 self
1478 }
1479 /// Identifies the authorization scope(s) for the method you are building.
1480 ///
1481 /// See [`Self::add_scope()`] for details.
1482 pub fn add_scopes<I, St>(mut self, scopes: I) -> DomainGetCall<'a, C>
1483 where
1484 I: IntoIterator<Item = St>,
1485 St: AsRef<str>,
1486 {
1487 self._scopes
1488 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1489 self
1490 }
1491
1492 /// Removes all scopes, and no default scope will be used either.
1493 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1494 /// for details).
1495 pub fn clear_scopes(mut self) -> DomainGetCall<'a, C> {
1496 self._scopes.clear();
1497 self
1498 }
1499}
1500
1501/// Lists the domains that have been registered by the client. The order of domains in the response is unspecified and non-deterministic. Newly created domains will not necessarily be added to the end of this list.
1502///
1503/// A builder for the *list* method supported by a *domain* resource.
1504/// It is not used directly, but through a [`DomainMethods`] instance.
1505///
1506/// # Example
1507///
1508/// Instantiate a resource method builder
1509///
1510/// ```test_harness,no_run
1511/// # extern crate hyper;
1512/// # extern crate hyper_rustls;
1513/// # extern crate google_gmailpostmastertools1 as gmailpostmastertools1;
1514/// # async fn dox() {
1515/// # use gmailpostmastertools1::{PostmasterTools, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1516///
1517/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1518/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1519/// # .with_native_roots()
1520/// # .unwrap()
1521/// # .https_only()
1522/// # .enable_http2()
1523/// # .build();
1524///
1525/// # let executor = hyper_util::rt::TokioExecutor::new();
1526/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1527/// # secret,
1528/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1529/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1530/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1531/// # ),
1532/// # ).build().await.unwrap();
1533///
1534/// # let client = hyper_util::client::legacy::Client::builder(
1535/// # hyper_util::rt::TokioExecutor::new()
1536/// # )
1537/// # .build(
1538/// # hyper_rustls::HttpsConnectorBuilder::new()
1539/// # .with_native_roots()
1540/// # .unwrap()
1541/// # .https_or_http()
1542/// # .enable_http2()
1543/// # .build()
1544/// # );
1545/// # let mut hub = PostmasterTools::new(client, auth);
1546/// // You can configure optional parameters by calling the respective setters at will, and
1547/// // execute the final call using `doit()`.
1548/// // Values shown here are possibly random and not representative !
1549/// let result = hub.domains().list()
1550/// .page_token("sed")
1551/// .page_size(-70)
1552/// .doit().await;
1553/// # }
1554/// ```
1555pub struct DomainListCall<'a, C>
1556where
1557 C: 'a,
1558{
1559 hub: &'a PostmasterTools<C>,
1560 _page_token: Option<String>,
1561 _page_size: Option<i32>,
1562 _delegate: Option<&'a mut dyn common::Delegate>,
1563 _additional_params: HashMap<String, String>,
1564 _scopes: BTreeSet<String>,
1565}
1566
1567impl<'a, C> common::CallBuilder for DomainListCall<'a, C> {}
1568
1569impl<'a, C> DomainListCall<'a, C>
1570where
1571 C: common::Connector,
1572{
1573 /// Perform the operation you have build so far.
1574 pub async fn doit(mut self) -> common::Result<(common::Response, ListDomainsResponse)> {
1575 use std::borrow::Cow;
1576 use std::io::{Read, Seek};
1577
1578 use common::{url::Params, ToParts};
1579 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1580
1581 let mut dd = common::DefaultDelegate;
1582 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1583 dlg.begin(common::MethodInfo {
1584 id: "gmailpostmastertools.domains.list",
1585 http_method: hyper::Method::GET,
1586 });
1587
1588 for &field in ["alt", "pageToken", "pageSize"].iter() {
1589 if self._additional_params.contains_key(field) {
1590 dlg.finished(false);
1591 return Err(common::Error::FieldClash(field));
1592 }
1593 }
1594
1595 let mut params = Params::with_capacity(4 + self._additional_params.len());
1596 if let Some(value) = self._page_token.as_ref() {
1597 params.push("pageToken", value);
1598 }
1599 if let Some(value) = self._page_size.as_ref() {
1600 params.push("pageSize", value.to_string());
1601 }
1602
1603 params.extend(self._additional_params.iter());
1604
1605 params.push("alt", "json");
1606 let mut url = self.hub._base_url.clone() + "v1/domains";
1607 if self._scopes.is_empty() {
1608 self._scopes
1609 .insert(Scope::PostmasterReadonly.as_ref().to_string());
1610 }
1611
1612 let url = params.parse_with_url(&url);
1613
1614 loop {
1615 let token = match self
1616 .hub
1617 .auth
1618 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1619 .await
1620 {
1621 Ok(token) => token,
1622 Err(e) => match dlg.token(e) {
1623 Ok(token) => token,
1624 Err(e) => {
1625 dlg.finished(false);
1626 return Err(common::Error::MissingToken(e));
1627 }
1628 },
1629 };
1630 let mut req_result = {
1631 let client = &self.hub.client;
1632 dlg.pre_request();
1633 let mut req_builder = hyper::Request::builder()
1634 .method(hyper::Method::GET)
1635 .uri(url.as_str())
1636 .header(USER_AGENT, self.hub._user_agent.clone());
1637
1638 if let Some(token) = token.as_ref() {
1639 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1640 }
1641
1642 let request = req_builder
1643 .header(CONTENT_LENGTH, 0_u64)
1644 .body(common::to_body::<String>(None));
1645
1646 client.request(request.unwrap()).await
1647 };
1648
1649 match req_result {
1650 Err(err) => {
1651 if let common::Retry::After(d) = dlg.http_error(&err) {
1652 sleep(d).await;
1653 continue;
1654 }
1655 dlg.finished(false);
1656 return Err(common::Error::HttpError(err));
1657 }
1658 Ok(res) => {
1659 let (mut parts, body) = res.into_parts();
1660 let mut body = common::Body::new(body);
1661 if !parts.status.is_success() {
1662 let bytes = common::to_bytes(body).await.unwrap_or_default();
1663 let error = serde_json::from_str(&common::to_string(&bytes));
1664 let response = common::to_response(parts, bytes.into());
1665
1666 if let common::Retry::After(d) =
1667 dlg.http_failure(&response, error.as_ref().ok())
1668 {
1669 sleep(d).await;
1670 continue;
1671 }
1672
1673 dlg.finished(false);
1674
1675 return Err(match error {
1676 Ok(value) => common::Error::BadRequest(value),
1677 _ => common::Error::Failure(response),
1678 });
1679 }
1680 let response = {
1681 let bytes = common::to_bytes(body).await.unwrap_or_default();
1682 let encoded = common::to_string(&bytes);
1683 match serde_json::from_str(&encoded) {
1684 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1685 Err(error) => {
1686 dlg.response_json_decode_error(&encoded, &error);
1687 return Err(common::Error::JsonDecodeError(
1688 encoded.to_string(),
1689 error,
1690 ));
1691 }
1692 }
1693 };
1694
1695 dlg.finished(true);
1696 return Ok(response);
1697 }
1698 }
1699 }
1700 }
1701
1702 /// The next_page_token value returned from a previous List request, if any. This is the value of ListDomainsResponse.next_page_token returned from the previous call to `ListDomains` method.
1703 ///
1704 /// Sets the *page token* query property to the given value.
1705 pub fn page_token(mut self, new_value: &str) -> DomainListCall<'a, C> {
1706 self._page_token = Some(new_value.to_string());
1707 self
1708 }
1709 /// Requested page size. Server may return fewer domains than requested. If unspecified, server will pick an appropriate default.
1710 ///
1711 /// Sets the *page size* query property to the given value.
1712 pub fn page_size(mut self, new_value: i32) -> DomainListCall<'a, C> {
1713 self._page_size = Some(new_value);
1714 self
1715 }
1716 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1717 /// while executing the actual API request.
1718 ///
1719 /// ````text
1720 /// It should be used to handle progress information, and to implement a certain level of resilience.
1721 /// ````
1722 ///
1723 /// Sets the *delegate* property to the given value.
1724 pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> DomainListCall<'a, C> {
1725 self._delegate = Some(new_value);
1726 self
1727 }
1728
1729 /// Set any additional parameter of the query string used in the request.
1730 /// It should be used to set parameters which are not yet available through their own
1731 /// setters.
1732 ///
1733 /// Please note that this method must not be used to set any of the known parameters
1734 /// which have their own setter method. If done anyway, the request will fail.
1735 ///
1736 /// # Additional Parameters
1737 ///
1738 /// * *$.xgafv* (query-string) - V1 error format.
1739 /// * *access_token* (query-string) - OAuth access token.
1740 /// * *alt* (query-string) - Data format for response.
1741 /// * *callback* (query-string) - JSONP
1742 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1743 /// * *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.
1744 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1745 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1746 /// * *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.
1747 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1748 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1749 pub fn param<T>(mut self, name: T, value: T) -> DomainListCall<'a, C>
1750 where
1751 T: AsRef<str>,
1752 {
1753 self._additional_params
1754 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1755 self
1756 }
1757
1758 /// Identifies the authorization scope for the method you are building.
1759 ///
1760 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1761 /// [`Scope::PostmasterReadonly`].
1762 ///
1763 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1764 /// tokens for more than one scope.
1765 ///
1766 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1767 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1768 /// sufficient, a read-write scope will do as well.
1769 pub fn add_scope<St>(mut self, scope: St) -> DomainListCall<'a, C>
1770 where
1771 St: AsRef<str>,
1772 {
1773 self._scopes.insert(String::from(scope.as_ref()));
1774 self
1775 }
1776 /// Identifies the authorization scope(s) for the method you are building.
1777 ///
1778 /// See [`Self::add_scope()`] for details.
1779 pub fn add_scopes<I, St>(mut self, scopes: I) -> DomainListCall<'a, C>
1780 where
1781 I: IntoIterator<Item = St>,
1782 St: AsRef<str>,
1783 {
1784 self._scopes
1785 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1786 self
1787 }
1788
1789 /// Removes all scopes, and no default scope will be used either.
1790 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1791 /// for details).
1792 pub fn clear_scopes(mut self) -> DomainListCall<'a, C> {
1793 self._scopes.clear();
1794 self
1795 }
1796}