google_indexing3/
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    /// Submit data to Google for indexing
17    Full,
18}
19
20impl AsRef<str> for Scope {
21    fn as_ref(&self) -> &str {
22        match *self {
23            Scope::Full => "https://www.googleapis.com/auth/indexing",
24        }
25    }
26}
27
28#[allow(clippy::derivable_impls)]
29impl Default for Scope {
30    fn default() -> Scope {
31        Scope::Full
32    }
33}
34
35// ########
36// HUB ###
37// ######
38
39/// Central instance to access all Indexing 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_indexing3 as indexing3;
49/// use indexing3::{Result, Error};
50/// # async fn dox() {
51/// use indexing3::{Indexing, 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 = Indexing::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.url_notifications().get_metadata()
82///              .url("no")
83///              .doit().await;
84///
85/// match result {
86///     Err(e) => match e {
87///         // The Error enum provides details about what exactly happened.
88///         // You can also just use its `Debug`, `Display` or `Error` traits
89///          Error::HttpError(_)
90///         |Error::Io(_)
91///         |Error::MissingAPIKey
92///         |Error::MissingToken(_)
93///         |Error::Cancelled
94///         |Error::UploadSizeLimitExceeded(_, _)
95///         |Error::Failure(_)
96///         |Error::BadRequest(_)
97///         |Error::FieldClash(_)
98///         |Error::JsonDecodeError(_, _) => println!("{}", e),
99///     },
100///     Ok(res) => println!("Success: {:?}", res),
101/// }
102/// # }
103/// ```
104#[derive(Clone)]
105pub struct Indexing<C> {
106    pub client: common::Client<C>,
107    pub auth: Box<dyn common::GetToken>,
108    _user_agent: String,
109    _base_url: String,
110    _root_url: String,
111}
112
113impl<C> common::Hub for Indexing<C> {}
114
115impl<'a, C> Indexing<C> {
116    pub fn new<A: 'static + common::GetToken>(client: common::Client<C>, auth: A) -> Indexing<C> {
117        Indexing {
118            client,
119            auth: Box::new(auth),
120            _user_agent: "google-api-rust-client/6.0.0".to_string(),
121            _base_url: "https://indexing.googleapis.com/".to_string(),
122            _root_url: "https://indexing.googleapis.com/".to_string(),
123        }
124    }
125
126    pub fn url_notifications(&'a self) -> UrlNotificationMethods<'a, C> {
127        UrlNotificationMethods { hub: self }
128    }
129
130    /// Set the user-agent header field to use in all requests to the server.
131    /// It defaults to `google-api-rust-client/6.0.0`.
132    ///
133    /// Returns the previously set user-agent.
134    pub fn user_agent(&mut self, agent_name: String) -> String {
135        std::mem::replace(&mut self._user_agent, agent_name)
136    }
137
138    /// Set the base url to use in all requests to the server.
139    /// It defaults to `https://indexing.googleapis.com/`.
140    ///
141    /// Returns the previously set base url.
142    pub fn base_url(&mut self, new_base_url: String) -> String {
143        std::mem::replace(&mut self._base_url, new_base_url)
144    }
145
146    /// Set the root url to use in all requests to the server.
147    /// It defaults to `https://indexing.googleapis.com/`.
148    ///
149    /// Returns the previously set root url.
150    pub fn root_url(&mut self, new_root_url: String) -> String {
151        std::mem::replace(&mut self._root_url, new_root_url)
152    }
153}
154
155// ############
156// SCHEMAS ###
157// ##########
158/// Output for PublishUrlNotification
159///
160/// # Activities
161///
162/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
163/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
164///
165/// * [publish url notifications](UrlNotificationPublishCall) (response)
166#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
167#[serde_with::serde_as]
168#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
169pub struct PublishUrlNotificationResponse {
170    /// Description of the notification events received for this URL.
171    #[serde(rename = "urlNotificationMetadata")]
172    pub url_notification_metadata: Option<UrlNotificationMetadata>,
173}
174
175impl common::ResponseResult for PublishUrlNotificationResponse {}
176
177/// `UrlNotification` is the resource used in all Indexing API calls. It describes one event in the life cycle of a Web Document.
178///
179/// # Activities
180///
181/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
182/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
183///
184/// * [get metadata url notifications](UrlNotificationGetMetadataCall) (none)
185/// * [publish url notifications](UrlNotificationPublishCall) (request)
186#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
187#[serde_with::serde_as]
188#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
189pub struct UrlNotification {
190    /// Creation timestamp for this notification. Users should _not_ specify it, the field is ignored at the request time.
191    #[serde(rename = "notifyTime")]
192    pub notify_time: Option<chrono::DateTime<chrono::offset::Utc>>,
193    /// The URL life cycle event that Google is being notified about.
194    #[serde(rename = "type")]
195    pub type_: Option<String>,
196    /// The object of this notification. The URL must be owned by the publisher of this notification and, in case of `URL_UPDATED` notifications, it _must_ be crawlable by Google.
197    pub url: Option<String>,
198}
199
200impl common::RequestValue for UrlNotification {}
201impl common::Resource for UrlNotification {}
202
203/// Summary of the most recent Indexing API notifications successfully received, for a given URL.
204///
205/// # Activities
206///
207/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
208/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
209///
210/// * [get metadata url notifications](UrlNotificationGetMetadataCall) (response)
211#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
212#[serde_with::serde_as]
213#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
214pub struct UrlNotificationMetadata {
215    /// Latest notification received with type `URL_REMOVED`.
216    #[serde(rename = "latestRemove")]
217    pub latest_remove: Option<UrlNotification>,
218    /// Latest notification received with type `URL_UPDATED`.
219    #[serde(rename = "latestUpdate")]
220    pub latest_update: Option<UrlNotification>,
221    /// URL to which this metadata refers.
222    pub url: Option<String>,
223}
224
225impl common::ResponseResult for UrlNotificationMetadata {}
226
227// ###################
228// MethodBuilders ###
229// #################
230
231/// A builder providing access to all methods supported on *urlNotification* resources.
232/// It is not used directly, but through the [`Indexing`] hub.
233///
234/// # Example
235///
236/// Instantiate a resource builder
237///
238/// ```test_harness,no_run
239/// extern crate hyper;
240/// extern crate hyper_rustls;
241/// extern crate google_indexing3 as indexing3;
242///
243/// # async fn dox() {
244/// use indexing3::{Indexing, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
245///
246/// let secret: yup_oauth2::ApplicationSecret = Default::default();
247/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
248///     secret,
249///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
250/// ).build().await.unwrap();
251///
252/// let client = hyper_util::client::legacy::Client::builder(
253///     hyper_util::rt::TokioExecutor::new()
254/// )
255/// .build(
256///     hyper_rustls::HttpsConnectorBuilder::new()
257///         .with_native_roots()
258///         .unwrap()
259///         .https_or_http()
260///         .enable_http1()
261///         .build()
262/// );
263/// let mut hub = Indexing::new(client, auth);
264/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
265/// // like `get_metadata(...)` and `publish(...)`
266/// // to build up your call.
267/// let rb = hub.url_notifications();
268/// # }
269/// ```
270pub struct UrlNotificationMethods<'a, C>
271where
272    C: 'a,
273{
274    hub: &'a Indexing<C>,
275}
276
277impl<'a, C> common::MethodsBuilder for UrlNotificationMethods<'a, C> {}
278
279impl<'a, C> UrlNotificationMethods<'a, C> {
280    /// Create a builder to help you perform the following task:
281    ///
282    /// Gets metadata about a Web Document. This method can _only_ be used to query URLs that were previously seen in successful Indexing API notifications. Includes the latest `UrlNotification` received via this API.
283    pub fn get_metadata(&self) -> UrlNotificationGetMetadataCall<'a, C> {
284        UrlNotificationGetMetadataCall {
285            hub: self.hub,
286            _url: Default::default(),
287            _delegate: Default::default(),
288            _additional_params: Default::default(),
289            _scopes: Default::default(),
290        }
291    }
292
293    /// Create a builder to help you perform the following task:
294    ///
295    /// Notifies that a URL has been updated or deleted.
296    ///
297    /// # Arguments
298    ///
299    /// * `request` - No description provided.
300    pub fn publish(&self, request: UrlNotification) -> UrlNotificationPublishCall<'a, C> {
301        UrlNotificationPublishCall {
302            hub: self.hub,
303            _request: request,
304            _delegate: Default::default(),
305            _additional_params: Default::default(),
306            _scopes: Default::default(),
307        }
308    }
309}
310
311// ###################
312// CallBuilders   ###
313// #################
314
315/// Gets metadata about a Web Document. This method can _only_ be used to query URLs that were previously seen in successful Indexing API notifications. Includes the latest `UrlNotification` received via this API.
316///
317/// A builder for the *getMetadata* method supported by a *urlNotification* resource.
318/// It is not used directly, but through a [`UrlNotificationMethods`] instance.
319///
320/// # Example
321///
322/// Instantiate a resource method builder
323///
324/// ```test_harness,no_run
325/// # extern crate hyper;
326/// # extern crate hyper_rustls;
327/// # extern crate google_indexing3 as indexing3;
328/// # async fn dox() {
329/// # use indexing3::{Indexing, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
330///
331/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
332/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
333/// #     secret,
334/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
335/// # ).build().await.unwrap();
336///
337/// # let client = hyper_util::client::legacy::Client::builder(
338/// #     hyper_util::rt::TokioExecutor::new()
339/// # )
340/// # .build(
341/// #     hyper_rustls::HttpsConnectorBuilder::new()
342/// #         .with_native_roots()
343/// #         .unwrap()
344/// #         .https_or_http()
345/// #         .enable_http1()
346/// #         .build()
347/// # );
348/// # let mut hub = Indexing::new(client, auth);
349/// // You can configure optional parameters by calling the respective setters at will, and
350/// // execute the final call using `doit()`.
351/// // Values shown here are possibly random and not representative !
352/// let result = hub.url_notifications().get_metadata()
353///              .url("ipsum")
354///              .doit().await;
355/// # }
356/// ```
357pub struct UrlNotificationGetMetadataCall<'a, C>
358where
359    C: 'a,
360{
361    hub: &'a Indexing<C>,
362    _url: Option<String>,
363    _delegate: Option<&'a mut dyn common::Delegate>,
364    _additional_params: HashMap<String, String>,
365    _scopes: BTreeSet<String>,
366}
367
368impl<'a, C> common::CallBuilder for UrlNotificationGetMetadataCall<'a, C> {}
369
370impl<'a, C> UrlNotificationGetMetadataCall<'a, C>
371where
372    C: common::Connector,
373{
374    /// Perform the operation you have build so far.
375    pub async fn doit(mut self) -> common::Result<(common::Response, UrlNotificationMetadata)> {
376        use std::borrow::Cow;
377        use std::io::{Read, Seek};
378
379        use common::{url::Params, ToParts};
380        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
381
382        let mut dd = common::DefaultDelegate;
383        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
384        dlg.begin(common::MethodInfo {
385            id: "indexing.urlNotifications.getMetadata",
386            http_method: hyper::Method::GET,
387        });
388
389        for &field in ["alt", "url"].iter() {
390            if self._additional_params.contains_key(field) {
391                dlg.finished(false);
392                return Err(common::Error::FieldClash(field));
393            }
394        }
395
396        let mut params = Params::with_capacity(3 + self._additional_params.len());
397        if let Some(value) = self._url.as_ref() {
398            params.push("url", value);
399        }
400
401        params.extend(self._additional_params.iter());
402
403        params.push("alt", "json");
404        let mut url = self.hub._base_url.clone() + "v3/urlNotifications/metadata";
405        if self._scopes.is_empty() {
406            self._scopes.insert(Scope::Full.as_ref().to_string());
407        }
408
409        let url = params.parse_with_url(&url);
410
411        loop {
412            let token = match self
413                .hub
414                .auth
415                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
416                .await
417            {
418                Ok(token) => token,
419                Err(e) => match dlg.token(e) {
420                    Ok(token) => token,
421                    Err(e) => {
422                        dlg.finished(false);
423                        return Err(common::Error::MissingToken(e));
424                    }
425                },
426            };
427            let mut req_result = {
428                let client = &self.hub.client;
429                dlg.pre_request();
430                let mut req_builder = hyper::Request::builder()
431                    .method(hyper::Method::GET)
432                    .uri(url.as_str())
433                    .header(USER_AGENT, self.hub._user_agent.clone());
434
435                if let Some(token) = token.as_ref() {
436                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
437                }
438
439                let request = req_builder
440                    .header(CONTENT_LENGTH, 0_u64)
441                    .body(common::to_body::<String>(None));
442
443                client.request(request.unwrap()).await
444            };
445
446            match req_result {
447                Err(err) => {
448                    if let common::Retry::After(d) = dlg.http_error(&err) {
449                        sleep(d).await;
450                        continue;
451                    }
452                    dlg.finished(false);
453                    return Err(common::Error::HttpError(err));
454                }
455                Ok(res) => {
456                    let (mut parts, body) = res.into_parts();
457                    let mut body = common::Body::new(body);
458                    if !parts.status.is_success() {
459                        let bytes = common::to_bytes(body).await.unwrap_or_default();
460                        let error = serde_json::from_str(&common::to_string(&bytes));
461                        let response = common::to_response(parts, bytes.into());
462
463                        if let common::Retry::After(d) =
464                            dlg.http_failure(&response, error.as_ref().ok())
465                        {
466                            sleep(d).await;
467                            continue;
468                        }
469
470                        dlg.finished(false);
471
472                        return Err(match error {
473                            Ok(value) => common::Error::BadRequest(value),
474                            _ => common::Error::Failure(response),
475                        });
476                    }
477                    let response = {
478                        let bytes = common::to_bytes(body).await.unwrap_or_default();
479                        let encoded = common::to_string(&bytes);
480                        match serde_json::from_str(&encoded) {
481                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
482                            Err(error) => {
483                                dlg.response_json_decode_error(&encoded, &error);
484                                return Err(common::Error::JsonDecodeError(
485                                    encoded.to_string(),
486                                    error,
487                                ));
488                            }
489                        }
490                    };
491
492                    dlg.finished(true);
493                    return Ok(response);
494                }
495            }
496        }
497    }
498
499    /// URL that is being queried.
500    ///
501    /// Sets the *url* query property to the given value.
502    pub fn url(mut self, new_value: &str) -> UrlNotificationGetMetadataCall<'a, C> {
503        self._url = Some(new_value.to_string());
504        self
505    }
506    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
507    /// while executing the actual API request.
508    ///
509    /// ````text
510    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
511    /// ````
512    ///
513    /// Sets the *delegate* property to the given value.
514    pub fn delegate(
515        mut self,
516        new_value: &'a mut dyn common::Delegate,
517    ) -> UrlNotificationGetMetadataCall<'a, C> {
518        self._delegate = Some(new_value);
519        self
520    }
521
522    /// Set any additional parameter of the query string used in the request.
523    /// It should be used to set parameters which are not yet available through their own
524    /// setters.
525    ///
526    /// Please note that this method must not be used to set any of the known parameters
527    /// which have their own setter method. If done anyway, the request will fail.
528    ///
529    /// # Additional Parameters
530    ///
531    /// * *$.xgafv* (query-string) - V1 error format.
532    /// * *access_token* (query-string) - OAuth access token.
533    /// * *alt* (query-string) - Data format for response.
534    /// * *callback* (query-string) - JSONP
535    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
536    /// * *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.
537    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
538    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
539    /// * *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.
540    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
541    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
542    pub fn param<T>(mut self, name: T, value: T) -> UrlNotificationGetMetadataCall<'a, C>
543    where
544        T: AsRef<str>,
545    {
546        self._additional_params
547            .insert(name.as_ref().to_string(), value.as_ref().to_string());
548        self
549    }
550
551    /// Identifies the authorization scope for the method you are building.
552    ///
553    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
554    /// [`Scope::Full`].
555    ///
556    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
557    /// tokens for more than one scope.
558    ///
559    /// Usually there is more than one suitable scope to authorize an operation, some of which may
560    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
561    /// sufficient, a read-write scope will do as well.
562    pub fn add_scope<St>(mut self, scope: St) -> UrlNotificationGetMetadataCall<'a, C>
563    where
564        St: AsRef<str>,
565    {
566        self._scopes.insert(String::from(scope.as_ref()));
567        self
568    }
569    /// Identifies the authorization scope(s) for the method you are building.
570    ///
571    /// See [`Self::add_scope()`] for details.
572    pub fn add_scopes<I, St>(mut self, scopes: I) -> UrlNotificationGetMetadataCall<'a, C>
573    where
574        I: IntoIterator<Item = St>,
575        St: AsRef<str>,
576    {
577        self._scopes
578            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
579        self
580    }
581
582    /// Removes all scopes, and no default scope will be used either.
583    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
584    /// for details).
585    pub fn clear_scopes(mut self) -> UrlNotificationGetMetadataCall<'a, C> {
586        self._scopes.clear();
587        self
588    }
589}
590
591/// Notifies that a URL has been updated or deleted.
592///
593/// A builder for the *publish* method supported by a *urlNotification* resource.
594/// It is not used directly, but through a [`UrlNotificationMethods`] instance.
595///
596/// # Example
597///
598/// Instantiate a resource method builder
599///
600/// ```test_harness,no_run
601/// # extern crate hyper;
602/// # extern crate hyper_rustls;
603/// # extern crate google_indexing3 as indexing3;
604/// use indexing3::api::UrlNotification;
605/// # async fn dox() {
606/// # use indexing3::{Indexing, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
607///
608/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
609/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
610/// #     secret,
611/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
612/// # ).build().await.unwrap();
613///
614/// # let client = hyper_util::client::legacy::Client::builder(
615/// #     hyper_util::rt::TokioExecutor::new()
616/// # )
617/// # .build(
618/// #     hyper_rustls::HttpsConnectorBuilder::new()
619/// #         .with_native_roots()
620/// #         .unwrap()
621/// #         .https_or_http()
622/// #         .enable_http1()
623/// #         .build()
624/// # );
625/// # let mut hub = Indexing::new(client, auth);
626/// // As the method needs a request, you would usually fill it with the desired information
627/// // into the respective structure. Some of the parts shown here might not be applicable !
628/// // Values shown here are possibly random and not representative !
629/// let mut req = UrlNotification::default();
630///
631/// // You can configure optional parameters by calling the respective setters at will, and
632/// // execute the final call using `doit()`.
633/// // Values shown here are possibly random and not representative !
634/// let result = hub.url_notifications().publish(req)
635///              .doit().await;
636/// # }
637/// ```
638pub struct UrlNotificationPublishCall<'a, C>
639where
640    C: 'a,
641{
642    hub: &'a Indexing<C>,
643    _request: UrlNotification,
644    _delegate: Option<&'a mut dyn common::Delegate>,
645    _additional_params: HashMap<String, String>,
646    _scopes: BTreeSet<String>,
647}
648
649impl<'a, C> common::CallBuilder for UrlNotificationPublishCall<'a, C> {}
650
651impl<'a, C> UrlNotificationPublishCall<'a, C>
652where
653    C: common::Connector,
654{
655    /// Perform the operation you have build so far.
656    pub async fn doit(
657        mut self,
658    ) -> common::Result<(common::Response, PublishUrlNotificationResponse)> {
659        use std::borrow::Cow;
660        use std::io::{Read, Seek};
661
662        use common::{url::Params, ToParts};
663        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
664
665        let mut dd = common::DefaultDelegate;
666        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
667        dlg.begin(common::MethodInfo {
668            id: "indexing.urlNotifications.publish",
669            http_method: hyper::Method::POST,
670        });
671
672        for &field in ["alt"].iter() {
673            if self._additional_params.contains_key(field) {
674                dlg.finished(false);
675                return Err(common::Error::FieldClash(field));
676            }
677        }
678
679        let mut params = Params::with_capacity(3 + self._additional_params.len());
680
681        params.extend(self._additional_params.iter());
682
683        params.push("alt", "json");
684        let mut url = self.hub._base_url.clone() + "v3/urlNotifications:publish";
685        if self._scopes.is_empty() {
686            self._scopes.insert(Scope::Full.as_ref().to_string());
687        }
688
689        let url = params.parse_with_url(&url);
690
691        let mut json_mime_type = mime::APPLICATION_JSON;
692        let mut request_value_reader = {
693            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
694            common::remove_json_null_values(&mut value);
695            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
696            serde_json::to_writer(&mut dst, &value).unwrap();
697            dst
698        };
699        let request_size = request_value_reader
700            .seek(std::io::SeekFrom::End(0))
701            .unwrap();
702        request_value_reader
703            .seek(std::io::SeekFrom::Start(0))
704            .unwrap();
705
706        loop {
707            let token = match self
708                .hub
709                .auth
710                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
711                .await
712            {
713                Ok(token) => token,
714                Err(e) => match dlg.token(e) {
715                    Ok(token) => token,
716                    Err(e) => {
717                        dlg.finished(false);
718                        return Err(common::Error::MissingToken(e));
719                    }
720                },
721            };
722            request_value_reader
723                .seek(std::io::SeekFrom::Start(0))
724                .unwrap();
725            let mut req_result = {
726                let client = &self.hub.client;
727                dlg.pre_request();
728                let mut req_builder = hyper::Request::builder()
729                    .method(hyper::Method::POST)
730                    .uri(url.as_str())
731                    .header(USER_AGENT, self.hub._user_agent.clone());
732
733                if let Some(token) = token.as_ref() {
734                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
735                }
736
737                let request = req_builder
738                    .header(CONTENT_TYPE, json_mime_type.to_string())
739                    .header(CONTENT_LENGTH, request_size as u64)
740                    .body(common::to_body(
741                        request_value_reader.get_ref().clone().into(),
742                    ));
743
744                client.request(request.unwrap()).await
745            };
746
747            match req_result {
748                Err(err) => {
749                    if let common::Retry::After(d) = dlg.http_error(&err) {
750                        sleep(d).await;
751                        continue;
752                    }
753                    dlg.finished(false);
754                    return Err(common::Error::HttpError(err));
755                }
756                Ok(res) => {
757                    let (mut parts, body) = res.into_parts();
758                    let mut body = common::Body::new(body);
759                    if !parts.status.is_success() {
760                        let bytes = common::to_bytes(body).await.unwrap_or_default();
761                        let error = serde_json::from_str(&common::to_string(&bytes));
762                        let response = common::to_response(parts, bytes.into());
763
764                        if let common::Retry::After(d) =
765                            dlg.http_failure(&response, error.as_ref().ok())
766                        {
767                            sleep(d).await;
768                            continue;
769                        }
770
771                        dlg.finished(false);
772
773                        return Err(match error {
774                            Ok(value) => common::Error::BadRequest(value),
775                            _ => common::Error::Failure(response),
776                        });
777                    }
778                    let response = {
779                        let bytes = common::to_bytes(body).await.unwrap_or_default();
780                        let encoded = common::to_string(&bytes);
781                        match serde_json::from_str(&encoded) {
782                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
783                            Err(error) => {
784                                dlg.response_json_decode_error(&encoded, &error);
785                                return Err(common::Error::JsonDecodeError(
786                                    encoded.to_string(),
787                                    error,
788                                ));
789                            }
790                        }
791                    };
792
793                    dlg.finished(true);
794                    return Ok(response);
795                }
796            }
797        }
798    }
799
800    ///
801    /// Sets the *request* property to the given value.
802    ///
803    /// Even though the property as already been set when instantiating this call,
804    /// we provide this method for API completeness.
805    pub fn request(mut self, new_value: UrlNotification) -> UrlNotificationPublishCall<'a, C> {
806        self._request = new_value;
807        self
808    }
809    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
810    /// while executing the actual API request.
811    ///
812    /// ````text
813    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
814    /// ````
815    ///
816    /// Sets the *delegate* property to the given value.
817    pub fn delegate(
818        mut self,
819        new_value: &'a mut dyn common::Delegate,
820    ) -> UrlNotificationPublishCall<'a, C> {
821        self._delegate = Some(new_value);
822        self
823    }
824
825    /// Set any additional parameter of the query string used in the request.
826    /// It should be used to set parameters which are not yet available through their own
827    /// setters.
828    ///
829    /// Please note that this method must not be used to set any of the known parameters
830    /// which have their own setter method. If done anyway, the request will fail.
831    ///
832    /// # Additional Parameters
833    ///
834    /// * *$.xgafv* (query-string) - V1 error format.
835    /// * *access_token* (query-string) - OAuth access token.
836    /// * *alt* (query-string) - Data format for response.
837    /// * *callback* (query-string) - JSONP
838    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
839    /// * *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.
840    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
841    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
842    /// * *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.
843    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
844    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
845    pub fn param<T>(mut self, name: T, value: T) -> UrlNotificationPublishCall<'a, C>
846    where
847        T: AsRef<str>,
848    {
849        self._additional_params
850            .insert(name.as_ref().to_string(), value.as_ref().to_string());
851        self
852    }
853
854    /// Identifies the authorization scope for the method you are building.
855    ///
856    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
857    /// [`Scope::Full`].
858    ///
859    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
860    /// tokens for more than one scope.
861    ///
862    /// Usually there is more than one suitable scope to authorize an operation, some of which may
863    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
864    /// sufficient, a read-write scope will do as well.
865    pub fn add_scope<St>(mut self, scope: St) -> UrlNotificationPublishCall<'a, C>
866    where
867        St: AsRef<str>,
868    {
869        self._scopes.insert(String::from(scope.as_ref()));
870        self
871    }
872    /// Identifies the authorization scope(s) for the method you are building.
873    ///
874    /// See [`Self::add_scope()`] for details.
875    pub fn add_scopes<I, St>(mut self, scopes: I) -> UrlNotificationPublishCall<'a, C>
876    where
877        I: IntoIterator<Item = St>,
878        St: AsRef<str>,
879    {
880        self._scopes
881            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
882        self
883    }
884
885    /// Removes all scopes, and no default scope will be used either.
886    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
887    /// for details).
888    pub fn clear_scopes(mut self) -> UrlNotificationPublishCall<'a, C> {
889        self._scopes.clear();
890        self
891    }
892}