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