google_translate2/
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    /// View and manage your data across Google Cloud Platform services
17    CloudPlatform,
18
19    /// Translate text from one language to another using Google Translate
20    CloudTranslation,
21}
22
23impl AsRef<str> for Scope {
24    fn as_ref(&self) -> &str {
25        match *self {
26            Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
27            Scope::CloudTranslation => "https://www.googleapis.com/auth/cloud-translation",
28        }
29    }
30}
31
32#[allow(clippy::derivable_impls)]
33impl Default for Scope {
34    fn default() -> Scope {
35        Scope::CloudPlatform
36    }
37}
38
39// ########
40// HUB ###
41// ######
42
43/// Central instance to access all Translate related resource activities
44///
45/// # Examples
46///
47/// Instantiate a new hub
48///
49/// ```test_harness,no_run
50/// extern crate hyper;
51/// extern crate hyper_rustls;
52/// extern crate google_translate2 as translate2;
53/// use translate2::api::DetectLanguageRequest;
54/// use translate2::{Result, Error};
55/// # async fn dox() {
56/// use translate2::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
57///
58/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
59/// // `client_secret`, among other things.
60/// let secret: yup_oauth2::ApplicationSecret = Default::default();
61/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
62/// // unless you replace  `None` with the desired Flow.
63/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
64/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
65/// // retrieve them from storage.
66/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
67///     secret,
68///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
69/// ).build().await.unwrap();
70///
71/// let client = hyper_util::client::legacy::Client::builder(
72///     hyper_util::rt::TokioExecutor::new()
73/// )
74/// .build(
75///     hyper_rustls::HttpsConnectorBuilder::new()
76///         .with_native_roots()
77///         .unwrap()
78///         .https_or_http()
79///         .enable_http1()
80///         .build()
81/// );
82/// let mut hub = Translate::new(client, auth);
83/// // As the method needs a request, you would usually fill it with the desired information
84/// // into the respective structure. Some of the parts shown here might not be applicable !
85/// // Values shown here are possibly random and not representative !
86/// let mut req = DetectLanguageRequest::default();
87///
88/// // You can configure optional parameters by calling the respective setters at will, and
89/// // execute the final call using `doit()`.
90/// // Values shown here are possibly random and not representative !
91/// let result = hub.detections().detect(req)
92///              .doit().await;
93///
94/// match result {
95///     Err(e) => match e {
96///         // The Error enum provides details about what exactly happened.
97///         // You can also just use its `Debug`, `Display` or `Error` traits
98///          Error::HttpError(_)
99///         |Error::Io(_)
100///         |Error::MissingAPIKey
101///         |Error::MissingToken(_)
102///         |Error::Cancelled
103///         |Error::UploadSizeLimitExceeded(_, _)
104///         |Error::Failure(_)
105///         |Error::BadRequest(_)
106///         |Error::FieldClash(_)
107///         |Error::JsonDecodeError(_, _) => println!("{}", e),
108///     },
109///     Ok(res) => println!("Success: {:?}", res),
110/// }
111/// # }
112/// ```
113#[derive(Clone)]
114pub struct Translate<C> {
115    pub client: common::Client<C>,
116    pub auth: Box<dyn common::GetToken>,
117    _user_agent: String,
118    _base_url: String,
119    _root_url: String,
120}
121
122impl<C> common::Hub for Translate<C> {}
123
124impl<'a, C> Translate<C> {
125    pub fn new<A: 'static + common::GetToken>(client: common::Client<C>, auth: A) -> Translate<C> {
126        Translate {
127            client,
128            auth: Box::new(auth),
129            _user_agent: "google-api-rust-client/6.0.0".to_string(),
130            _base_url: "https://translation.googleapis.com/language/translate/".to_string(),
131            _root_url: "https://translation.googleapis.com/".to_string(),
132        }
133    }
134
135    pub fn detections(&'a self) -> DetectionMethods<'a, C> {
136        DetectionMethods { hub: self }
137    }
138    pub fn languages(&'a self) -> LanguageMethods<'a, C> {
139        LanguageMethods { hub: self }
140    }
141    pub fn translations(&'a self) -> TranslationMethods<'a, C> {
142        TranslationMethods { hub: self }
143    }
144
145    /// Set the user-agent header field to use in all requests to the server.
146    /// It defaults to `google-api-rust-client/6.0.0`.
147    ///
148    /// Returns the previously set user-agent.
149    pub fn user_agent(&mut self, agent_name: String) -> String {
150        std::mem::replace(&mut self._user_agent, agent_name)
151    }
152
153    /// Set the base url to use in all requests to the server.
154    /// It defaults to `https://translation.googleapis.com/language/translate/`.
155    ///
156    /// Returns the previously set base url.
157    pub fn base_url(&mut self, new_base_url: String) -> String {
158        std::mem::replace(&mut self._base_url, new_base_url)
159    }
160
161    /// Set the root url to use in all requests to the server.
162    /// It defaults to `https://translation.googleapis.com/`.
163    ///
164    /// Returns the previously set root url.
165    pub fn root_url(&mut self, new_root_url: String) -> String {
166        std::mem::replace(&mut self._root_url, new_root_url)
167    }
168}
169
170// ############
171// SCHEMAS ###
172// ##########
173/// The request message for language detection.
174///
175/// # Activities
176///
177/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
178/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
179///
180/// * [detect detections](DetectionDetectCall) (request)
181#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
182#[serde_with::serde_as]
183#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
184pub struct DetectLanguageRequest {
185    /// The input text upon which to perform language detection. Repeat this
186    /// parameter to perform language detection on multiple text inputs.
187    pub q: Option<Vec<String>>,
188}
189
190impl common::RequestValue for DetectLanguageRequest {}
191
192/// There is no detailed description.
193///
194/// # Activities
195///
196/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
197/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
198///
199/// * [detect detections](DetectionDetectCall) (response)
200/// * [list detections](DetectionListCall) (response)
201#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
202#[serde_with::serde_as]
203#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
204pub struct DetectionsListResponse {
205    /// A detections contains detection results of several text
206    pub detections: Option<Vec<DetectionsResource>>,
207}
208
209impl common::ResponseResult for DetectionsListResponse {}
210
211/// An array of languages which we detect for the given text The most likely language list first.
212///
213/// This type is not used in any activity, and only used as *part* of another schema.
214///
215/// The contained type is `Option<Vec<DetectionsResourceDetectionsResource>>`.
216///
217#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
218#[serde_with::serde_as]
219#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
220pub struct DetectionsResource {
221    /// The confidence of the detection result of this language.
222    pub confidence: Option<f32>,
223    /// A boolean to indicate is the language detection result reliable.
224    #[serde(rename = "isReliable")]
225    pub is_reliable: Option<bool>,
226    /// The language we detected.
227    pub language: Option<String>,
228}
229
230impl common::Part for DetectionsResource {}
231
232/// There is no detailed description.
233///
234/// # Activities
235///
236/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
237/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
238///
239/// * [list languages](LanguageListCall) (response)
240#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
241#[serde_with::serde_as]
242#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
243pub struct LanguagesListResponse {
244    /// List of source/target languages supported by the translation API. If target parameter is unspecified, the list is sorted by the ASCII code point order of the language code. If target parameter is specified, the list is sorted by the collation order of the language name in the target language.
245    pub languages: Option<Vec<LanguagesResource>>,
246}
247
248impl common::ResponseResult for LanguagesListResponse {}
249
250/// There is no detailed description.
251///
252/// This type is not used in any activity, and only used as *part* of another schema.
253///
254#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
255#[serde_with::serde_as]
256#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
257pub struct LanguagesResource {
258    /// Supported language code, generally consisting of its ISO 639-1
259    /// identifier. (E.g. 'en', 'ja'). In certain cases, BCP-47 codes including
260    /// language + region identifiers are returned (e.g. 'zh-TW' and 'zh-CH')
261    pub language: Option<String>,
262    /// Human readable name of the language localized to the target language.
263    pub name: Option<String>,
264}
265
266impl common::Part for LanguagesResource {}
267
268/// The main translation request message for the Cloud Translation API.
269///
270/// # Activities
271///
272/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
273/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
274///
275/// * [translate translations](TranslationTranslateCall) (request)
276#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
277#[serde_with::serde_as]
278#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
279pub struct TranslateTextRequest {
280    /// The format of the source text, in either HTML (default) or plain-text. A
281    /// value of "html" indicates HTML and a value of "text" indicates plain-text.
282    pub format: Option<String>,
283    /// The `model` type requested for this translation. Valid values are
284    /// listed in public documentation.
285    pub model: Option<String>,
286    /// The input text to translate. Repeat this parameter to perform translation
287    /// operations on multiple text inputs.
288    pub q: Option<Vec<String>>,
289    /// The language of the source text, set to one of the language codes listed in
290    /// Language Support. If the source language is not specified, the API will
291    /// attempt to identify the source language automatically and return it within
292    /// the response.
293    pub source: Option<String>,
294    /// The language to use for translation of the input text, set to one of the
295    /// language codes listed in Language Support.
296    pub target: Option<String>,
297}
298
299impl common::RequestValue for TranslateTextRequest {}
300
301/// The main language translation response message.
302///
303/// # Activities
304///
305/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
306/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
307///
308/// * [list translations](TranslationListCall) (response)
309/// * [translate translations](TranslationTranslateCall) (response)
310#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
311#[serde_with::serde_as]
312#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
313pub struct TranslationsListResponse {
314    /// Translations contains list of translation results of given text
315    pub translations: Option<Vec<TranslationsResource>>,
316}
317
318impl common::ResponseResult for TranslationsListResponse {}
319
320/// There is no detailed description.
321///
322/// This type is not used in any activity, and only used as *part* of another schema.
323///
324#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
325#[serde_with::serde_as]
326#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
327pub struct TranslationsResource {
328    /// The source language of the initial request, detected automatically, if
329    /// no source language was passed within the initial request. If the
330    /// source language was passed, auto-detection of the language will not
331    /// occur and this field will be empty.
332    #[serde(rename = "detectedSourceLanguage")]
333    pub detected_source_language: Option<String>,
334    /// The `model` type used for this translation. Valid values are
335    /// listed in public documentation. Can be different from requested `model`.
336    /// Present only if specific model type was explicitly requested.
337    pub model: Option<String>,
338    /// Text translated into the target language.
339    #[serde(rename = "translatedText")]
340    pub translated_text: Option<String>,
341}
342
343impl common::Part for TranslationsResource {}
344
345/// An array of languages which we detect for the given text The most likely language list first.
346///
347/// This type is not used in any activity, and only used as *part* of another schema.
348///
349#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
350#[serde_with::serde_as]
351#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
352pub struct DetectionsResourceNested {
353    /// The confidence of the detection result of this language.
354    pub confidence: Option<f32>,
355    /// A boolean to indicate is the language detection result reliable.
356    #[serde(rename = "isReliable")]
357    pub is_reliable: Option<bool>,
358    /// The language we detected.
359    pub language: Option<String>,
360}
361
362impl common::NestedType for DetectionsResourceNested {}
363impl common::Part for DetectionsResourceNested {}
364
365// ###################
366// MethodBuilders ###
367// #################
368
369/// A builder providing access to all methods supported on *detection* resources.
370/// It is not used directly, but through the [`Translate`] hub.
371///
372/// # Example
373///
374/// Instantiate a resource builder
375///
376/// ```test_harness,no_run
377/// extern crate hyper;
378/// extern crate hyper_rustls;
379/// extern crate google_translate2 as translate2;
380///
381/// # async fn dox() {
382/// use translate2::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
383///
384/// let secret: yup_oauth2::ApplicationSecret = Default::default();
385/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
386///     secret,
387///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
388/// ).build().await.unwrap();
389///
390/// let client = hyper_util::client::legacy::Client::builder(
391///     hyper_util::rt::TokioExecutor::new()
392/// )
393/// .build(
394///     hyper_rustls::HttpsConnectorBuilder::new()
395///         .with_native_roots()
396///         .unwrap()
397///         .https_or_http()
398///         .enable_http1()
399///         .build()
400/// );
401/// let mut hub = Translate::new(client, auth);
402/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
403/// // like `detect(...)` and `list(...)`
404/// // to build up your call.
405/// let rb = hub.detections();
406/// # }
407/// ```
408pub struct DetectionMethods<'a, C>
409where
410    C: 'a,
411{
412    hub: &'a Translate<C>,
413}
414
415impl<'a, C> common::MethodsBuilder for DetectionMethods<'a, C> {}
416
417impl<'a, C> DetectionMethods<'a, C> {
418    /// Create a builder to help you perform the following task:
419    ///
420    /// Detects the language of text within a request.
421    ///
422    /// # Arguments
423    ///
424    /// * `request` - No description provided.
425    pub fn detect(&self, request: DetectLanguageRequest) -> DetectionDetectCall<'a, C> {
426        DetectionDetectCall {
427            hub: self.hub,
428            _request: request,
429            _delegate: Default::default(),
430            _additional_params: Default::default(),
431            _scopes: Default::default(),
432        }
433    }
434
435    /// Create a builder to help you perform the following task:
436    ///
437    /// Detects the language of text within a request.
438    ///
439    /// # Arguments
440    ///
441    /// * `q` - The input text upon which to perform language detection. Repeat this
442    ///         parameter to perform language detection on multiple text inputs.
443    pub fn list(&self, q: &Vec<String>) -> DetectionListCall<'a, C> {
444        DetectionListCall {
445            hub: self.hub,
446            _q: q.clone(),
447            _delegate: Default::default(),
448            _additional_params: Default::default(),
449            _scopes: Default::default(),
450        }
451    }
452}
453
454/// A builder providing access to all methods supported on *language* resources.
455/// It is not used directly, but through the [`Translate`] hub.
456///
457/// # Example
458///
459/// Instantiate a resource builder
460///
461/// ```test_harness,no_run
462/// extern crate hyper;
463/// extern crate hyper_rustls;
464/// extern crate google_translate2 as translate2;
465///
466/// # async fn dox() {
467/// use translate2::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
468///
469/// let secret: yup_oauth2::ApplicationSecret = Default::default();
470/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
471///     secret,
472///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
473/// ).build().await.unwrap();
474///
475/// let client = hyper_util::client::legacy::Client::builder(
476///     hyper_util::rt::TokioExecutor::new()
477/// )
478/// .build(
479///     hyper_rustls::HttpsConnectorBuilder::new()
480///         .with_native_roots()
481///         .unwrap()
482///         .https_or_http()
483///         .enable_http1()
484///         .build()
485/// );
486/// let mut hub = Translate::new(client, auth);
487/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
488/// // like `list(...)`
489/// // to build up your call.
490/// let rb = hub.languages();
491/// # }
492/// ```
493pub struct LanguageMethods<'a, C>
494where
495    C: 'a,
496{
497    hub: &'a Translate<C>,
498}
499
500impl<'a, C> common::MethodsBuilder for LanguageMethods<'a, C> {}
501
502impl<'a, C> LanguageMethods<'a, C> {
503    /// Create a builder to help you perform the following task:
504    ///
505    /// Returns a list of supported languages for translation.
506    pub fn list(&self) -> LanguageListCall<'a, C> {
507        LanguageListCall {
508            hub: self.hub,
509            _target: Default::default(),
510            _model: Default::default(),
511            _delegate: Default::default(),
512            _additional_params: Default::default(),
513            _scopes: Default::default(),
514        }
515    }
516}
517
518/// A builder providing access to all methods supported on *translation* resources.
519/// It is not used directly, but through the [`Translate`] hub.
520///
521/// # Example
522///
523/// Instantiate a resource builder
524///
525/// ```test_harness,no_run
526/// extern crate hyper;
527/// extern crate hyper_rustls;
528/// extern crate google_translate2 as translate2;
529///
530/// # async fn dox() {
531/// use translate2::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
532///
533/// let secret: yup_oauth2::ApplicationSecret = Default::default();
534/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
535///     secret,
536///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
537/// ).build().await.unwrap();
538///
539/// let client = hyper_util::client::legacy::Client::builder(
540///     hyper_util::rt::TokioExecutor::new()
541/// )
542/// .build(
543///     hyper_rustls::HttpsConnectorBuilder::new()
544///         .with_native_roots()
545///         .unwrap()
546///         .https_or_http()
547///         .enable_http1()
548///         .build()
549/// );
550/// let mut hub = Translate::new(client, auth);
551/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
552/// // like `list(...)` and `translate(...)`
553/// // to build up your call.
554/// let rb = hub.translations();
555/// # }
556/// ```
557pub struct TranslationMethods<'a, C>
558where
559    C: 'a,
560{
561    hub: &'a Translate<C>,
562}
563
564impl<'a, C> common::MethodsBuilder for TranslationMethods<'a, C> {}
565
566impl<'a, C> TranslationMethods<'a, C> {
567    /// Create a builder to help you perform the following task:
568    ///
569    /// Translates input text, returning translated text.
570    ///
571    /// # Arguments
572    ///
573    /// * `q` - The input text to translate. Repeat this parameter to perform translation
574    ///         operations on multiple text inputs.
575    /// * `target` - The language to use for translation of the input text, set to one of the
576    ///              language codes listed in Language Support.
577    pub fn list(&self, q: &Vec<String>, target: &str) -> TranslationListCall<'a, C> {
578        TranslationListCall {
579            hub: self.hub,
580            _q: q.clone(),
581            _target: target.to_string(),
582            _source: Default::default(),
583            _model: Default::default(),
584            _format: Default::default(),
585            _cid: Default::default(),
586            _delegate: Default::default(),
587            _additional_params: Default::default(),
588            _scopes: Default::default(),
589        }
590    }
591
592    /// Create a builder to help you perform the following task:
593    ///
594    /// Translates input text, returning translated text.
595    ///
596    /// # Arguments
597    ///
598    /// * `request` - No description provided.
599    pub fn translate(&self, request: TranslateTextRequest) -> TranslationTranslateCall<'a, C> {
600        TranslationTranslateCall {
601            hub: self.hub,
602            _request: request,
603            _delegate: Default::default(),
604            _additional_params: Default::default(),
605            _scopes: Default::default(),
606        }
607    }
608}
609
610// ###################
611// CallBuilders   ###
612// #################
613
614/// Detects the language of text within a request.
615///
616/// A builder for the *detect* method supported by a *detection* resource.
617/// It is not used directly, but through a [`DetectionMethods`] instance.
618///
619/// # Example
620///
621/// Instantiate a resource method builder
622///
623/// ```test_harness,no_run
624/// # extern crate hyper;
625/// # extern crate hyper_rustls;
626/// # extern crate google_translate2 as translate2;
627/// use translate2::api::DetectLanguageRequest;
628/// # async fn dox() {
629/// # use translate2::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
630///
631/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
632/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
633/// #     secret,
634/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
635/// # ).build().await.unwrap();
636///
637/// # let client = hyper_util::client::legacy::Client::builder(
638/// #     hyper_util::rt::TokioExecutor::new()
639/// # )
640/// # .build(
641/// #     hyper_rustls::HttpsConnectorBuilder::new()
642/// #         .with_native_roots()
643/// #         .unwrap()
644/// #         .https_or_http()
645/// #         .enable_http1()
646/// #         .build()
647/// # );
648/// # let mut hub = Translate::new(client, auth);
649/// // As the method needs a request, you would usually fill it with the desired information
650/// // into the respective structure. Some of the parts shown here might not be applicable !
651/// // Values shown here are possibly random and not representative !
652/// let mut req = DetectLanguageRequest::default();
653///
654/// // You can configure optional parameters by calling the respective setters at will, and
655/// // execute the final call using `doit()`.
656/// // Values shown here are possibly random and not representative !
657/// let result = hub.detections().detect(req)
658///              .doit().await;
659/// # }
660/// ```
661pub struct DetectionDetectCall<'a, C>
662where
663    C: 'a,
664{
665    hub: &'a Translate<C>,
666    _request: DetectLanguageRequest,
667    _delegate: Option<&'a mut dyn common::Delegate>,
668    _additional_params: HashMap<String, String>,
669    _scopes: BTreeSet<String>,
670}
671
672impl<'a, C> common::CallBuilder for DetectionDetectCall<'a, C> {}
673
674impl<'a, C> DetectionDetectCall<'a, C>
675where
676    C: common::Connector,
677{
678    /// Perform the operation you have build so far.
679    pub async fn doit(mut self) -> common::Result<(common::Response, DetectionsListResponse)> {
680        use std::borrow::Cow;
681        use std::io::{Read, Seek};
682
683        use common::{url::Params, ToParts};
684        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
685
686        let mut dd = common::DefaultDelegate;
687        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
688        dlg.begin(common::MethodInfo {
689            id: "language.detections.detect",
690            http_method: hyper::Method::POST,
691        });
692
693        for &field in ["alt"].iter() {
694            if self._additional_params.contains_key(field) {
695                dlg.finished(false);
696                return Err(common::Error::FieldClash(field));
697            }
698        }
699
700        let mut params = Params::with_capacity(3 + self._additional_params.len());
701
702        params.extend(self._additional_params.iter());
703
704        params.push("alt", "json");
705        let mut url = self.hub._base_url.clone() + "v2/detect";
706        if self._scopes.is_empty() {
707            self._scopes
708                .insert(Scope::CloudPlatform.as_ref().to_string());
709        }
710
711        let url = params.parse_with_url(&url);
712
713        let mut json_mime_type = mime::APPLICATION_JSON;
714        let mut request_value_reader = {
715            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
716            common::remove_json_null_values(&mut value);
717            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
718            serde_json::to_writer(&mut dst, &value).unwrap();
719            dst
720        };
721        let request_size = request_value_reader
722            .seek(std::io::SeekFrom::End(0))
723            .unwrap();
724        request_value_reader
725            .seek(std::io::SeekFrom::Start(0))
726            .unwrap();
727
728        loop {
729            let token = match self
730                .hub
731                .auth
732                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
733                .await
734            {
735                Ok(token) => token,
736                Err(e) => match dlg.token(e) {
737                    Ok(token) => token,
738                    Err(e) => {
739                        dlg.finished(false);
740                        return Err(common::Error::MissingToken(e));
741                    }
742                },
743            };
744            request_value_reader
745                .seek(std::io::SeekFrom::Start(0))
746                .unwrap();
747            let mut req_result = {
748                let client = &self.hub.client;
749                dlg.pre_request();
750                let mut req_builder = hyper::Request::builder()
751                    .method(hyper::Method::POST)
752                    .uri(url.as_str())
753                    .header(USER_AGENT, self.hub._user_agent.clone());
754
755                if let Some(token) = token.as_ref() {
756                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
757                }
758
759                let request = req_builder
760                    .header(CONTENT_TYPE, json_mime_type.to_string())
761                    .header(CONTENT_LENGTH, request_size as u64)
762                    .body(common::to_body(
763                        request_value_reader.get_ref().clone().into(),
764                    ));
765
766                client.request(request.unwrap()).await
767            };
768
769            match req_result {
770                Err(err) => {
771                    if let common::Retry::After(d) = dlg.http_error(&err) {
772                        sleep(d).await;
773                        continue;
774                    }
775                    dlg.finished(false);
776                    return Err(common::Error::HttpError(err));
777                }
778                Ok(res) => {
779                    let (mut parts, body) = res.into_parts();
780                    let mut body = common::Body::new(body);
781                    if !parts.status.is_success() {
782                        let bytes = common::to_bytes(body).await.unwrap_or_default();
783                        let error = serde_json::from_str(&common::to_string(&bytes));
784                        let response = common::to_response(parts, bytes.into());
785
786                        if let common::Retry::After(d) =
787                            dlg.http_failure(&response, error.as_ref().ok())
788                        {
789                            sleep(d).await;
790                            continue;
791                        }
792
793                        dlg.finished(false);
794
795                        return Err(match error {
796                            Ok(value) => common::Error::BadRequest(value),
797                            _ => common::Error::Failure(response),
798                        });
799                    }
800                    let response = {
801                        let bytes = common::to_bytes(body).await.unwrap_or_default();
802                        let encoded = common::to_string(&bytes);
803                        match serde_json::from_str(&encoded) {
804                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
805                            Err(error) => {
806                                dlg.response_json_decode_error(&encoded, &error);
807                                return Err(common::Error::JsonDecodeError(
808                                    encoded.to_string(),
809                                    error,
810                                ));
811                            }
812                        }
813                    };
814
815                    dlg.finished(true);
816                    return Ok(response);
817                }
818            }
819        }
820    }
821
822    ///
823    /// Sets the *request* property to the given value.
824    ///
825    /// Even though the property as already been set when instantiating this call,
826    /// we provide this method for API completeness.
827    pub fn request(mut self, new_value: DetectLanguageRequest) -> DetectionDetectCall<'a, C> {
828        self._request = new_value;
829        self
830    }
831    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
832    /// while executing the actual API request.
833    ///
834    /// ````text
835    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
836    /// ````
837    ///
838    /// Sets the *delegate* property to the given value.
839    pub fn delegate(
840        mut self,
841        new_value: &'a mut dyn common::Delegate,
842    ) -> DetectionDetectCall<'a, C> {
843        self._delegate = Some(new_value);
844        self
845    }
846
847    /// Set any additional parameter of the query string used in the request.
848    /// It should be used to set parameters which are not yet available through their own
849    /// setters.
850    ///
851    /// Please note that this method must not be used to set any of the known parameters
852    /// which have their own setter method. If done anyway, the request will fail.
853    ///
854    /// # Additional Parameters
855    ///
856    /// * *$.xgafv* (query-string) - V1 error format.
857    /// * *access_token* (query-string) - OAuth access token.
858    /// * *alt* (query-string) - Data format for response.
859    /// * *bearer_token* (query-string) - OAuth bearer token.
860    /// * *callback* (query-string) - JSONP
861    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
862    /// * *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.
863    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
864    /// * *pp* (query-boolean) - Pretty-print response.
865    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
866    /// * *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. Overrides userIp if both are provided.
867    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
868    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
869    pub fn param<T>(mut self, name: T, value: T) -> DetectionDetectCall<'a, C>
870    where
871        T: AsRef<str>,
872    {
873        self._additional_params
874            .insert(name.as_ref().to_string(), value.as_ref().to_string());
875        self
876    }
877
878    /// Identifies the authorization scope for the method you are building.
879    ///
880    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
881    /// [`Scope::CloudPlatform`].
882    ///
883    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
884    /// tokens for more than one scope.
885    ///
886    /// Usually there is more than one suitable scope to authorize an operation, some of which may
887    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
888    /// sufficient, a read-write scope will do as well.
889    pub fn add_scope<St>(mut self, scope: St) -> DetectionDetectCall<'a, C>
890    where
891        St: AsRef<str>,
892    {
893        self._scopes.insert(String::from(scope.as_ref()));
894        self
895    }
896    /// Identifies the authorization scope(s) for the method you are building.
897    ///
898    /// See [`Self::add_scope()`] for details.
899    pub fn add_scopes<I, St>(mut self, scopes: I) -> DetectionDetectCall<'a, C>
900    where
901        I: IntoIterator<Item = St>,
902        St: AsRef<str>,
903    {
904        self._scopes
905            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
906        self
907    }
908
909    /// Removes all scopes, and no default scope will be used either.
910    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
911    /// for details).
912    pub fn clear_scopes(mut self) -> DetectionDetectCall<'a, C> {
913        self._scopes.clear();
914        self
915    }
916}
917
918/// Detects the language of text within a request.
919///
920/// A builder for the *list* method supported by a *detection* resource.
921/// It is not used directly, but through a [`DetectionMethods`] instance.
922///
923/// # Example
924///
925/// Instantiate a resource method builder
926///
927/// ```test_harness,no_run
928/// # extern crate hyper;
929/// # extern crate hyper_rustls;
930/// # extern crate google_translate2 as translate2;
931/// # async fn dox() {
932/// # use translate2::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
933///
934/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
935/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
936/// #     secret,
937/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
938/// # ).build().await.unwrap();
939///
940/// # let client = hyper_util::client::legacy::Client::builder(
941/// #     hyper_util::rt::TokioExecutor::new()
942/// # )
943/// # .build(
944/// #     hyper_rustls::HttpsConnectorBuilder::new()
945/// #         .with_native_roots()
946/// #         .unwrap()
947/// #         .https_or_http()
948/// #         .enable_http1()
949/// #         .build()
950/// # );
951/// # let mut hub = Translate::new(client, auth);
952/// // You can configure optional parameters by calling the respective setters at will, and
953/// // execute the final call using `doit()`.
954/// // Values shown here are possibly random and not representative !
955/// let result = hub.detections().list(&vec!["et".into()])
956///              .doit().await;
957/// # }
958/// ```
959pub struct DetectionListCall<'a, C>
960where
961    C: 'a,
962{
963    hub: &'a Translate<C>,
964    _q: Vec<String>,
965    _delegate: Option<&'a mut dyn common::Delegate>,
966    _additional_params: HashMap<String, String>,
967    _scopes: BTreeSet<String>,
968}
969
970impl<'a, C> common::CallBuilder for DetectionListCall<'a, C> {}
971
972impl<'a, C> DetectionListCall<'a, C>
973where
974    C: common::Connector,
975{
976    /// Perform the operation you have build so far.
977    pub async fn doit(mut self) -> common::Result<(common::Response, DetectionsListResponse)> {
978        use std::borrow::Cow;
979        use std::io::{Read, Seek};
980
981        use common::{url::Params, ToParts};
982        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
983
984        let mut dd = common::DefaultDelegate;
985        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
986        dlg.begin(common::MethodInfo {
987            id: "language.detections.list",
988            http_method: hyper::Method::GET,
989        });
990
991        for &field in ["alt", "q"].iter() {
992            if self._additional_params.contains_key(field) {
993                dlg.finished(false);
994                return Err(common::Error::FieldClash(field));
995            }
996        }
997
998        let mut params = Params::with_capacity(3 + self._additional_params.len());
999        if !self._q.is_empty() {
1000            for f in self._q.iter() {
1001                params.push("q", f);
1002            }
1003        }
1004
1005        params.extend(self._additional_params.iter());
1006
1007        params.push("alt", "json");
1008        let mut url = self.hub._base_url.clone() + "v2/detect";
1009        if self._scopes.is_empty() {
1010            self._scopes
1011                .insert(Scope::CloudPlatform.as_ref().to_string());
1012        }
1013
1014        let url = params.parse_with_url(&url);
1015
1016        loop {
1017            let token = match self
1018                .hub
1019                .auth
1020                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1021                .await
1022            {
1023                Ok(token) => token,
1024                Err(e) => match dlg.token(e) {
1025                    Ok(token) => token,
1026                    Err(e) => {
1027                        dlg.finished(false);
1028                        return Err(common::Error::MissingToken(e));
1029                    }
1030                },
1031            };
1032            let mut req_result = {
1033                let client = &self.hub.client;
1034                dlg.pre_request();
1035                let mut req_builder = hyper::Request::builder()
1036                    .method(hyper::Method::GET)
1037                    .uri(url.as_str())
1038                    .header(USER_AGENT, self.hub._user_agent.clone());
1039
1040                if let Some(token) = token.as_ref() {
1041                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1042                }
1043
1044                let request = req_builder
1045                    .header(CONTENT_LENGTH, 0_u64)
1046                    .body(common::to_body::<String>(None));
1047
1048                client.request(request.unwrap()).await
1049            };
1050
1051            match req_result {
1052                Err(err) => {
1053                    if let common::Retry::After(d) = dlg.http_error(&err) {
1054                        sleep(d).await;
1055                        continue;
1056                    }
1057                    dlg.finished(false);
1058                    return Err(common::Error::HttpError(err));
1059                }
1060                Ok(res) => {
1061                    let (mut parts, body) = res.into_parts();
1062                    let mut body = common::Body::new(body);
1063                    if !parts.status.is_success() {
1064                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1065                        let error = serde_json::from_str(&common::to_string(&bytes));
1066                        let response = common::to_response(parts, bytes.into());
1067
1068                        if let common::Retry::After(d) =
1069                            dlg.http_failure(&response, error.as_ref().ok())
1070                        {
1071                            sleep(d).await;
1072                            continue;
1073                        }
1074
1075                        dlg.finished(false);
1076
1077                        return Err(match error {
1078                            Ok(value) => common::Error::BadRequest(value),
1079                            _ => common::Error::Failure(response),
1080                        });
1081                    }
1082                    let response = {
1083                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1084                        let encoded = common::to_string(&bytes);
1085                        match serde_json::from_str(&encoded) {
1086                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1087                            Err(error) => {
1088                                dlg.response_json_decode_error(&encoded, &error);
1089                                return Err(common::Error::JsonDecodeError(
1090                                    encoded.to_string(),
1091                                    error,
1092                                ));
1093                            }
1094                        }
1095                    };
1096
1097                    dlg.finished(true);
1098                    return Ok(response);
1099                }
1100            }
1101        }
1102    }
1103
1104    /// The input text upon which to perform language detection. Repeat this
1105    /// parameter to perform language detection on multiple text inputs.
1106    ///
1107    /// Append the given value to the *q* query property.
1108    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
1109    ///
1110    /// Even though the property as already been set when instantiating this call,
1111    /// we provide this method for API completeness.
1112    pub fn add_q(mut self, new_value: &str) -> DetectionListCall<'a, C> {
1113        self._q.push(new_value.to_string());
1114        self
1115    }
1116    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1117    /// while executing the actual API request.
1118    ///
1119    /// ````text
1120    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1121    /// ````
1122    ///
1123    /// Sets the *delegate* property to the given value.
1124    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> DetectionListCall<'a, C> {
1125        self._delegate = Some(new_value);
1126        self
1127    }
1128
1129    /// Set any additional parameter of the query string used in the request.
1130    /// It should be used to set parameters which are not yet available through their own
1131    /// setters.
1132    ///
1133    /// Please note that this method must not be used to set any of the known parameters
1134    /// which have their own setter method. If done anyway, the request will fail.
1135    ///
1136    /// # Additional Parameters
1137    ///
1138    /// * *$.xgafv* (query-string) - V1 error format.
1139    /// * *access_token* (query-string) - OAuth access token.
1140    /// * *alt* (query-string) - Data format for response.
1141    /// * *bearer_token* (query-string) - OAuth bearer token.
1142    /// * *callback* (query-string) - JSONP
1143    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1144    /// * *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.
1145    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1146    /// * *pp* (query-boolean) - Pretty-print response.
1147    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1148    /// * *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. Overrides userIp if both are provided.
1149    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1150    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1151    pub fn param<T>(mut self, name: T, value: T) -> DetectionListCall<'a, C>
1152    where
1153        T: AsRef<str>,
1154    {
1155        self._additional_params
1156            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1157        self
1158    }
1159
1160    /// Identifies the authorization scope for the method you are building.
1161    ///
1162    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1163    /// [`Scope::CloudPlatform`].
1164    ///
1165    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1166    /// tokens for more than one scope.
1167    ///
1168    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1169    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1170    /// sufficient, a read-write scope will do as well.
1171    pub fn add_scope<St>(mut self, scope: St) -> DetectionListCall<'a, C>
1172    where
1173        St: AsRef<str>,
1174    {
1175        self._scopes.insert(String::from(scope.as_ref()));
1176        self
1177    }
1178    /// Identifies the authorization scope(s) for the method you are building.
1179    ///
1180    /// See [`Self::add_scope()`] for details.
1181    pub fn add_scopes<I, St>(mut self, scopes: I) -> DetectionListCall<'a, C>
1182    where
1183        I: IntoIterator<Item = St>,
1184        St: AsRef<str>,
1185    {
1186        self._scopes
1187            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1188        self
1189    }
1190
1191    /// Removes all scopes, and no default scope will be used either.
1192    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1193    /// for details).
1194    pub fn clear_scopes(mut self) -> DetectionListCall<'a, C> {
1195        self._scopes.clear();
1196        self
1197    }
1198}
1199
1200/// Returns a list of supported languages for translation.
1201///
1202/// A builder for the *list* method supported by a *language* resource.
1203/// It is not used directly, but through a [`LanguageMethods`] instance.
1204///
1205/// # Example
1206///
1207/// Instantiate a resource method builder
1208///
1209/// ```test_harness,no_run
1210/// # extern crate hyper;
1211/// # extern crate hyper_rustls;
1212/// # extern crate google_translate2 as translate2;
1213/// # async fn dox() {
1214/// # use translate2::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1215///
1216/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1217/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1218/// #     secret,
1219/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1220/// # ).build().await.unwrap();
1221///
1222/// # let client = hyper_util::client::legacy::Client::builder(
1223/// #     hyper_util::rt::TokioExecutor::new()
1224/// # )
1225/// # .build(
1226/// #     hyper_rustls::HttpsConnectorBuilder::new()
1227/// #         .with_native_roots()
1228/// #         .unwrap()
1229/// #         .https_or_http()
1230/// #         .enable_http1()
1231/// #         .build()
1232/// # );
1233/// # let mut hub = Translate::new(client, auth);
1234/// // You can configure optional parameters by calling the respective setters at will, and
1235/// // execute the final call using `doit()`.
1236/// // Values shown here are possibly random and not representative !
1237/// let result = hub.languages().list()
1238///              .target("magna")
1239///              .model("no")
1240///              .doit().await;
1241/// # }
1242/// ```
1243pub struct LanguageListCall<'a, C>
1244where
1245    C: 'a,
1246{
1247    hub: &'a Translate<C>,
1248    _target: Option<String>,
1249    _model: Option<String>,
1250    _delegate: Option<&'a mut dyn common::Delegate>,
1251    _additional_params: HashMap<String, String>,
1252    _scopes: BTreeSet<String>,
1253}
1254
1255impl<'a, C> common::CallBuilder for LanguageListCall<'a, C> {}
1256
1257impl<'a, C> LanguageListCall<'a, C>
1258where
1259    C: common::Connector,
1260{
1261    /// Perform the operation you have build so far.
1262    pub async fn doit(mut self) -> common::Result<(common::Response, LanguagesListResponse)> {
1263        use std::borrow::Cow;
1264        use std::io::{Read, Seek};
1265
1266        use common::{url::Params, ToParts};
1267        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1268
1269        let mut dd = common::DefaultDelegate;
1270        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1271        dlg.begin(common::MethodInfo {
1272            id: "language.languages.list",
1273            http_method: hyper::Method::GET,
1274        });
1275
1276        for &field in ["alt", "target", "model"].iter() {
1277            if self._additional_params.contains_key(field) {
1278                dlg.finished(false);
1279                return Err(common::Error::FieldClash(field));
1280            }
1281        }
1282
1283        let mut params = Params::with_capacity(4 + self._additional_params.len());
1284        if let Some(value) = self._target.as_ref() {
1285            params.push("target", value);
1286        }
1287        if let Some(value) = self._model.as_ref() {
1288            params.push("model", value);
1289        }
1290
1291        params.extend(self._additional_params.iter());
1292
1293        params.push("alt", "json");
1294        let mut url = self.hub._base_url.clone() + "v2/languages";
1295        if self._scopes.is_empty() {
1296            self._scopes
1297                .insert(Scope::CloudPlatform.as_ref().to_string());
1298        }
1299
1300        let url = params.parse_with_url(&url);
1301
1302        loop {
1303            let token = match self
1304                .hub
1305                .auth
1306                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1307                .await
1308            {
1309                Ok(token) => token,
1310                Err(e) => match dlg.token(e) {
1311                    Ok(token) => token,
1312                    Err(e) => {
1313                        dlg.finished(false);
1314                        return Err(common::Error::MissingToken(e));
1315                    }
1316                },
1317            };
1318            let mut req_result = {
1319                let client = &self.hub.client;
1320                dlg.pre_request();
1321                let mut req_builder = hyper::Request::builder()
1322                    .method(hyper::Method::GET)
1323                    .uri(url.as_str())
1324                    .header(USER_AGENT, self.hub._user_agent.clone());
1325
1326                if let Some(token) = token.as_ref() {
1327                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1328                }
1329
1330                let request = req_builder
1331                    .header(CONTENT_LENGTH, 0_u64)
1332                    .body(common::to_body::<String>(None));
1333
1334                client.request(request.unwrap()).await
1335            };
1336
1337            match req_result {
1338                Err(err) => {
1339                    if let common::Retry::After(d) = dlg.http_error(&err) {
1340                        sleep(d).await;
1341                        continue;
1342                    }
1343                    dlg.finished(false);
1344                    return Err(common::Error::HttpError(err));
1345                }
1346                Ok(res) => {
1347                    let (mut parts, body) = res.into_parts();
1348                    let mut body = common::Body::new(body);
1349                    if !parts.status.is_success() {
1350                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1351                        let error = serde_json::from_str(&common::to_string(&bytes));
1352                        let response = common::to_response(parts, bytes.into());
1353
1354                        if let common::Retry::After(d) =
1355                            dlg.http_failure(&response, error.as_ref().ok())
1356                        {
1357                            sleep(d).await;
1358                            continue;
1359                        }
1360
1361                        dlg.finished(false);
1362
1363                        return Err(match error {
1364                            Ok(value) => common::Error::BadRequest(value),
1365                            _ => common::Error::Failure(response),
1366                        });
1367                    }
1368                    let response = {
1369                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1370                        let encoded = common::to_string(&bytes);
1371                        match serde_json::from_str(&encoded) {
1372                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1373                            Err(error) => {
1374                                dlg.response_json_decode_error(&encoded, &error);
1375                                return Err(common::Error::JsonDecodeError(
1376                                    encoded.to_string(),
1377                                    error,
1378                                ));
1379                            }
1380                        }
1381                    };
1382
1383                    dlg.finished(true);
1384                    return Ok(response);
1385                }
1386            }
1387        }
1388    }
1389
1390    /// The language to use to return localized, human readable names of supported
1391    /// languages.
1392    ///
1393    /// Sets the *target* query property to the given value.
1394    pub fn target(mut self, new_value: &str) -> LanguageListCall<'a, C> {
1395        self._target = Some(new_value.to_string());
1396        self
1397    }
1398    /// The model type for which supported languages should be returned.
1399    ///
1400    /// Sets the *model* query property to the given value.
1401    pub fn model(mut self, new_value: &str) -> LanguageListCall<'a, C> {
1402        self._model = Some(new_value.to_string());
1403        self
1404    }
1405    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1406    /// while executing the actual API request.
1407    ///
1408    /// ````text
1409    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1410    /// ````
1411    ///
1412    /// Sets the *delegate* property to the given value.
1413    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> LanguageListCall<'a, C> {
1414        self._delegate = Some(new_value);
1415        self
1416    }
1417
1418    /// Set any additional parameter of the query string used in the request.
1419    /// It should be used to set parameters which are not yet available through their own
1420    /// setters.
1421    ///
1422    /// Please note that this method must not be used to set any of the known parameters
1423    /// which have their own setter method. If done anyway, the request will fail.
1424    ///
1425    /// # Additional Parameters
1426    ///
1427    /// * *$.xgafv* (query-string) - V1 error format.
1428    /// * *access_token* (query-string) - OAuth access token.
1429    /// * *alt* (query-string) - Data format for response.
1430    /// * *bearer_token* (query-string) - OAuth bearer token.
1431    /// * *callback* (query-string) - JSONP
1432    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1433    /// * *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.
1434    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1435    /// * *pp* (query-boolean) - Pretty-print response.
1436    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1437    /// * *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. Overrides userIp if both are provided.
1438    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1439    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1440    pub fn param<T>(mut self, name: T, value: T) -> LanguageListCall<'a, C>
1441    where
1442        T: AsRef<str>,
1443    {
1444        self._additional_params
1445            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1446        self
1447    }
1448
1449    /// Identifies the authorization scope for the method you are building.
1450    ///
1451    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1452    /// [`Scope::CloudPlatform`].
1453    ///
1454    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1455    /// tokens for more than one scope.
1456    ///
1457    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1458    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1459    /// sufficient, a read-write scope will do as well.
1460    pub fn add_scope<St>(mut self, scope: St) -> LanguageListCall<'a, C>
1461    where
1462        St: AsRef<str>,
1463    {
1464        self._scopes.insert(String::from(scope.as_ref()));
1465        self
1466    }
1467    /// Identifies the authorization scope(s) for the method you are building.
1468    ///
1469    /// See [`Self::add_scope()`] for details.
1470    pub fn add_scopes<I, St>(mut self, scopes: I) -> LanguageListCall<'a, C>
1471    where
1472        I: IntoIterator<Item = St>,
1473        St: AsRef<str>,
1474    {
1475        self._scopes
1476            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1477        self
1478    }
1479
1480    /// Removes all scopes, and no default scope will be used either.
1481    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1482    /// for details).
1483    pub fn clear_scopes(mut self) -> LanguageListCall<'a, C> {
1484        self._scopes.clear();
1485        self
1486    }
1487}
1488
1489/// Translates input text, returning translated text.
1490///
1491/// A builder for the *list* method supported by a *translation* resource.
1492/// It is not used directly, but through a [`TranslationMethods`] instance.
1493///
1494/// # Example
1495///
1496/// Instantiate a resource method builder
1497///
1498/// ```test_harness,no_run
1499/// # extern crate hyper;
1500/// # extern crate hyper_rustls;
1501/// # extern crate google_translate2 as translate2;
1502/// # async fn dox() {
1503/// # use translate2::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1504///
1505/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1506/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1507/// #     secret,
1508/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1509/// # ).build().await.unwrap();
1510///
1511/// # let client = hyper_util::client::legacy::Client::builder(
1512/// #     hyper_util::rt::TokioExecutor::new()
1513/// # )
1514/// # .build(
1515/// #     hyper_rustls::HttpsConnectorBuilder::new()
1516/// #         .with_native_roots()
1517/// #         .unwrap()
1518/// #         .https_or_http()
1519/// #         .enable_http1()
1520/// #         .build()
1521/// # );
1522/// # let mut hub = Translate::new(client, auth);
1523/// // You can configure optional parameters by calling the respective setters at will, and
1524/// // execute the final call using `doit()`.
1525/// // Values shown here are possibly random and not representative !
1526/// let result = hub.translations().list(&vec!["ipsum".into()], "target")
1527///              .source("At")
1528///              .model("sanctus")
1529///              .format("sed")
1530///              .add_cid("amet.")
1531///              .doit().await;
1532/// # }
1533/// ```
1534pub struct TranslationListCall<'a, C>
1535where
1536    C: 'a,
1537{
1538    hub: &'a Translate<C>,
1539    _q: Vec<String>,
1540    _target: String,
1541    _source: Option<String>,
1542    _model: Option<String>,
1543    _format: Option<String>,
1544    _cid: Vec<String>,
1545    _delegate: Option<&'a mut dyn common::Delegate>,
1546    _additional_params: HashMap<String, String>,
1547    _scopes: BTreeSet<String>,
1548}
1549
1550impl<'a, C> common::CallBuilder for TranslationListCall<'a, C> {}
1551
1552impl<'a, C> TranslationListCall<'a, C>
1553where
1554    C: common::Connector,
1555{
1556    /// Perform the operation you have build so far.
1557    pub async fn doit(mut self) -> common::Result<(common::Response, TranslationsListResponse)> {
1558        use std::borrow::Cow;
1559        use std::io::{Read, Seek};
1560
1561        use common::{url::Params, ToParts};
1562        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1563
1564        let mut dd = common::DefaultDelegate;
1565        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1566        dlg.begin(common::MethodInfo {
1567            id: "language.translations.list",
1568            http_method: hyper::Method::GET,
1569        });
1570
1571        for &field in ["alt", "q", "target", "source", "model", "format", "cid"].iter() {
1572            if self._additional_params.contains_key(field) {
1573                dlg.finished(false);
1574                return Err(common::Error::FieldClash(field));
1575            }
1576        }
1577
1578        let mut params = Params::with_capacity(8 + self._additional_params.len());
1579        if !self._q.is_empty() {
1580            for f in self._q.iter() {
1581                params.push("q", f);
1582            }
1583        }
1584        params.push("target", self._target);
1585        if let Some(value) = self._source.as_ref() {
1586            params.push("source", value);
1587        }
1588        if let Some(value) = self._model.as_ref() {
1589            params.push("model", value);
1590        }
1591        if let Some(value) = self._format.as_ref() {
1592            params.push("format", value);
1593        }
1594        if !self._cid.is_empty() {
1595            for f in self._cid.iter() {
1596                params.push("cid", f);
1597            }
1598        }
1599
1600        params.extend(self._additional_params.iter());
1601
1602        params.push("alt", "json");
1603        let mut url = self.hub._base_url.clone() + "v2";
1604        if self._scopes.is_empty() {
1605            self._scopes
1606                .insert(Scope::CloudPlatform.as_ref().to_string());
1607        }
1608
1609        let url = params.parse_with_url(&url);
1610
1611        loop {
1612            let token = match self
1613                .hub
1614                .auth
1615                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1616                .await
1617            {
1618                Ok(token) => token,
1619                Err(e) => match dlg.token(e) {
1620                    Ok(token) => token,
1621                    Err(e) => {
1622                        dlg.finished(false);
1623                        return Err(common::Error::MissingToken(e));
1624                    }
1625                },
1626            };
1627            let mut req_result = {
1628                let client = &self.hub.client;
1629                dlg.pre_request();
1630                let mut req_builder = hyper::Request::builder()
1631                    .method(hyper::Method::GET)
1632                    .uri(url.as_str())
1633                    .header(USER_AGENT, self.hub._user_agent.clone());
1634
1635                if let Some(token) = token.as_ref() {
1636                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1637                }
1638
1639                let request = req_builder
1640                    .header(CONTENT_LENGTH, 0_u64)
1641                    .body(common::to_body::<String>(None));
1642
1643                client.request(request.unwrap()).await
1644            };
1645
1646            match req_result {
1647                Err(err) => {
1648                    if let common::Retry::After(d) = dlg.http_error(&err) {
1649                        sleep(d).await;
1650                        continue;
1651                    }
1652                    dlg.finished(false);
1653                    return Err(common::Error::HttpError(err));
1654                }
1655                Ok(res) => {
1656                    let (mut parts, body) = res.into_parts();
1657                    let mut body = common::Body::new(body);
1658                    if !parts.status.is_success() {
1659                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1660                        let error = serde_json::from_str(&common::to_string(&bytes));
1661                        let response = common::to_response(parts, bytes.into());
1662
1663                        if let common::Retry::After(d) =
1664                            dlg.http_failure(&response, error.as_ref().ok())
1665                        {
1666                            sleep(d).await;
1667                            continue;
1668                        }
1669
1670                        dlg.finished(false);
1671
1672                        return Err(match error {
1673                            Ok(value) => common::Error::BadRequest(value),
1674                            _ => common::Error::Failure(response),
1675                        });
1676                    }
1677                    let response = {
1678                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1679                        let encoded = common::to_string(&bytes);
1680                        match serde_json::from_str(&encoded) {
1681                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1682                            Err(error) => {
1683                                dlg.response_json_decode_error(&encoded, &error);
1684                                return Err(common::Error::JsonDecodeError(
1685                                    encoded.to_string(),
1686                                    error,
1687                                ));
1688                            }
1689                        }
1690                    };
1691
1692                    dlg.finished(true);
1693                    return Ok(response);
1694                }
1695            }
1696        }
1697    }
1698
1699    /// The input text to translate. Repeat this parameter to perform translation
1700    /// operations on multiple text inputs.
1701    ///
1702    /// Append the given value to the *q* query property.
1703    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
1704    ///
1705    /// Even though the property as already been set when instantiating this call,
1706    /// we provide this method for API completeness.
1707    pub fn add_q(mut self, new_value: &str) -> TranslationListCall<'a, C> {
1708        self._q.push(new_value.to_string());
1709        self
1710    }
1711    /// The language to use for translation of the input text, set to one of the
1712    /// language codes listed in Language Support.
1713    ///
1714    /// Sets the *target* query property to the given value.
1715    ///
1716    /// Even though the property as already been set when instantiating this call,
1717    /// we provide this method for API completeness.
1718    pub fn target(mut self, new_value: &str) -> TranslationListCall<'a, C> {
1719        self._target = new_value.to_string();
1720        self
1721    }
1722    /// The language of the source text, set to one of the language codes listed in
1723    /// Language Support. If the source language is not specified, the API will
1724    /// attempt to identify the source language automatically and return it within
1725    /// the response.
1726    ///
1727    /// Sets the *source* query property to the given value.
1728    pub fn source(mut self, new_value: &str) -> TranslationListCall<'a, C> {
1729        self._source = Some(new_value.to_string());
1730        self
1731    }
1732    /// The `model` type requested for this translation. Valid values are
1733    /// listed in public documentation.
1734    ///
1735    /// Sets the *model* query property to the given value.
1736    pub fn model(mut self, new_value: &str) -> TranslationListCall<'a, C> {
1737        self._model = Some(new_value.to_string());
1738        self
1739    }
1740    /// The format of the source text, in either HTML (default) or plain-text. A
1741    /// value of "html" indicates HTML and a value of "text" indicates plain-text.
1742    ///
1743    /// Sets the *format* query property to the given value.
1744    pub fn format(mut self, new_value: &str) -> TranslationListCall<'a, C> {
1745        self._format = Some(new_value.to_string());
1746        self
1747    }
1748    /// The customization id for translate
1749    ///
1750    /// Append the given value to the *cid* query property.
1751    /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
1752    pub fn add_cid(mut self, new_value: &str) -> TranslationListCall<'a, C> {
1753        self._cid.push(new_value.to_string());
1754        self
1755    }
1756    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1757    /// while executing the actual API request.
1758    ///
1759    /// ````text
1760    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1761    /// ````
1762    ///
1763    /// Sets the *delegate* property to the given value.
1764    pub fn delegate(
1765        mut self,
1766        new_value: &'a mut dyn common::Delegate,
1767    ) -> TranslationListCall<'a, C> {
1768        self._delegate = Some(new_value);
1769        self
1770    }
1771
1772    /// Set any additional parameter of the query string used in the request.
1773    /// It should be used to set parameters which are not yet available through their own
1774    /// setters.
1775    ///
1776    /// Please note that this method must not be used to set any of the known parameters
1777    /// which have their own setter method. If done anyway, the request will fail.
1778    ///
1779    /// # Additional Parameters
1780    ///
1781    /// * *$.xgafv* (query-string) - V1 error format.
1782    /// * *access_token* (query-string) - OAuth access token.
1783    /// * *alt* (query-string) - Data format for response.
1784    /// * *bearer_token* (query-string) - OAuth bearer token.
1785    /// * *callback* (query-string) - JSONP
1786    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1787    /// * *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.
1788    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1789    /// * *pp* (query-boolean) - Pretty-print response.
1790    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1791    /// * *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. Overrides userIp if both are provided.
1792    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1793    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1794    pub fn param<T>(mut self, name: T, value: T) -> TranslationListCall<'a, C>
1795    where
1796        T: AsRef<str>,
1797    {
1798        self._additional_params
1799            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1800        self
1801    }
1802
1803    /// Identifies the authorization scope for the method you are building.
1804    ///
1805    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1806    /// [`Scope::CloudPlatform`].
1807    ///
1808    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1809    /// tokens for more than one scope.
1810    ///
1811    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1812    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1813    /// sufficient, a read-write scope will do as well.
1814    pub fn add_scope<St>(mut self, scope: St) -> TranslationListCall<'a, C>
1815    where
1816        St: AsRef<str>,
1817    {
1818        self._scopes.insert(String::from(scope.as_ref()));
1819        self
1820    }
1821    /// Identifies the authorization scope(s) for the method you are building.
1822    ///
1823    /// See [`Self::add_scope()`] for details.
1824    pub fn add_scopes<I, St>(mut self, scopes: I) -> TranslationListCall<'a, C>
1825    where
1826        I: IntoIterator<Item = St>,
1827        St: AsRef<str>,
1828    {
1829        self._scopes
1830            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1831        self
1832    }
1833
1834    /// Removes all scopes, and no default scope will be used either.
1835    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1836    /// for details).
1837    pub fn clear_scopes(mut self) -> TranslationListCall<'a, C> {
1838        self._scopes.clear();
1839        self
1840    }
1841}
1842
1843/// Translates input text, returning translated text.
1844///
1845/// A builder for the *translate* method supported by a *translation* resource.
1846/// It is not used directly, but through a [`TranslationMethods`] instance.
1847///
1848/// # Example
1849///
1850/// Instantiate a resource method builder
1851///
1852/// ```test_harness,no_run
1853/// # extern crate hyper;
1854/// # extern crate hyper_rustls;
1855/// # extern crate google_translate2 as translate2;
1856/// use translate2::api::TranslateTextRequest;
1857/// # async fn dox() {
1858/// # use translate2::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1859///
1860/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1861/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1862/// #     secret,
1863/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1864/// # ).build().await.unwrap();
1865///
1866/// # let client = hyper_util::client::legacy::Client::builder(
1867/// #     hyper_util::rt::TokioExecutor::new()
1868/// # )
1869/// # .build(
1870/// #     hyper_rustls::HttpsConnectorBuilder::new()
1871/// #         .with_native_roots()
1872/// #         .unwrap()
1873/// #         .https_or_http()
1874/// #         .enable_http1()
1875/// #         .build()
1876/// # );
1877/// # let mut hub = Translate::new(client, auth);
1878/// // As the method needs a request, you would usually fill it with the desired information
1879/// // into the respective structure. Some of the parts shown here might not be applicable !
1880/// // Values shown here are possibly random and not representative !
1881/// let mut req = TranslateTextRequest::default();
1882///
1883/// // You can configure optional parameters by calling the respective setters at will, and
1884/// // execute the final call using `doit()`.
1885/// // Values shown here are possibly random and not representative !
1886/// let result = hub.translations().translate(req)
1887///              .doit().await;
1888/// # }
1889/// ```
1890pub struct TranslationTranslateCall<'a, C>
1891where
1892    C: 'a,
1893{
1894    hub: &'a Translate<C>,
1895    _request: TranslateTextRequest,
1896    _delegate: Option<&'a mut dyn common::Delegate>,
1897    _additional_params: HashMap<String, String>,
1898    _scopes: BTreeSet<String>,
1899}
1900
1901impl<'a, C> common::CallBuilder for TranslationTranslateCall<'a, C> {}
1902
1903impl<'a, C> TranslationTranslateCall<'a, C>
1904where
1905    C: common::Connector,
1906{
1907    /// Perform the operation you have build so far.
1908    pub async fn doit(mut self) -> common::Result<(common::Response, TranslationsListResponse)> {
1909        use std::borrow::Cow;
1910        use std::io::{Read, Seek};
1911
1912        use common::{url::Params, ToParts};
1913        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1914
1915        let mut dd = common::DefaultDelegate;
1916        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1917        dlg.begin(common::MethodInfo {
1918            id: "language.translations.translate",
1919            http_method: hyper::Method::POST,
1920        });
1921
1922        for &field in ["alt"].iter() {
1923            if self._additional_params.contains_key(field) {
1924                dlg.finished(false);
1925                return Err(common::Error::FieldClash(field));
1926            }
1927        }
1928
1929        let mut params = Params::with_capacity(3 + self._additional_params.len());
1930
1931        params.extend(self._additional_params.iter());
1932
1933        params.push("alt", "json");
1934        let mut url = self.hub._base_url.clone() + "v2";
1935        if self._scopes.is_empty() {
1936            self._scopes
1937                .insert(Scope::CloudPlatform.as_ref().to_string());
1938        }
1939
1940        let url = params.parse_with_url(&url);
1941
1942        let mut json_mime_type = mime::APPLICATION_JSON;
1943        let mut request_value_reader = {
1944            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1945            common::remove_json_null_values(&mut value);
1946            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1947            serde_json::to_writer(&mut dst, &value).unwrap();
1948            dst
1949        };
1950        let request_size = request_value_reader
1951            .seek(std::io::SeekFrom::End(0))
1952            .unwrap();
1953        request_value_reader
1954            .seek(std::io::SeekFrom::Start(0))
1955            .unwrap();
1956
1957        loop {
1958            let token = match self
1959                .hub
1960                .auth
1961                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1962                .await
1963            {
1964                Ok(token) => token,
1965                Err(e) => match dlg.token(e) {
1966                    Ok(token) => token,
1967                    Err(e) => {
1968                        dlg.finished(false);
1969                        return Err(common::Error::MissingToken(e));
1970                    }
1971                },
1972            };
1973            request_value_reader
1974                .seek(std::io::SeekFrom::Start(0))
1975                .unwrap();
1976            let mut req_result = {
1977                let client = &self.hub.client;
1978                dlg.pre_request();
1979                let mut req_builder = hyper::Request::builder()
1980                    .method(hyper::Method::POST)
1981                    .uri(url.as_str())
1982                    .header(USER_AGENT, self.hub._user_agent.clone());
1983
1984                if let Some(token) = token.as_ref() {
1985                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1986                }
1987
1988                let request = req_builder
1989                    .header(CONTENT_TYPE, json_mime_type.to_string())
1990                    .header(CONTENT_LENGTH, request_size as u64)
1991                    .body(common::to_body(
1992                        request_value_reader.get_ref().clone().into(),
1993                    ));
1994
1995                client.request(request.unwrap()).await
1996            };
1997
1998            match req_result {
1999                Err(err) => {
2000                    if let common::Retry::After(d) = dlg.http_error(&err) {
2001                        sleep(d).await;
2002                        continue;
2003                    }
2004                    dlg.finished(false);
2005                    return Err(common::Error::HttpError(err));
2006                }
2007                Ok(res) => {
2008                    let (mut parts, body) = res.into_parts();
2009                    let mut body = common::Body::new(body);
2010                    if !parts.status.is_success() {
2011                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2012                        let error = serde_json::from_str(&common::to_string(&bytes));
2013                        let response = common::to_response(parts, bytes.into());
2014
2015                        if let common::Retry::After(d) =
2016                            dlg.http_failure(&response, error.as_ref().ok())
2017                        {
2018                            sleep(d).await;
2019                            continue;
2020                        }
2021
2022                        dlg.finished(false);
2023
2024                        return Err(match error {
2025                            Ok(value) => common::Error::BadRequest(value),
2026                            _ => common::Error::Failure(response),
2027                        });
2028                    }
2029                    let response = {
2030                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2031                        let encoded = common::to_string(&bytes);
2032                        match serde_json::from_str(&encoded) {
2033                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2034                            Err(error) => {
2035                                dlg.response_json_decode_error(&encoded, &error);
2036                                return Err(common::Error::JsonDecodeError(
2037                                    encoded.to_string(),
2038                                    error,
2039                                ));
2040                            }
2041                        }
2042                    };
2043
2044                    dlg.finished(true);
2045                    return Ok(response);
2046                }
2047            }
2048        }
2049    }
2050
2051    ///
2052    /// Sets the *request* property to the given value.
2053    ///
2054    /// Even though the property as already been set when instantiating this call,
2055    /// we provide this method for API completeness.
2056    pub fn request(mut self, new_value: TranslateTextRequest) -> TranslationTranslateCall<'a, C> {
2057        self._request = new_value;
2058        self
2059    }
2060    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2061    /// while executing the actual API request.
2062    ///
2063    /// ````text
2064    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
2065    /// ````
2066    ///
2067    /// Sets the *delegate* property to the given value.
2068    pub fn delegate(
2069        mut self,
2070        new_value: &'a mut dyn common::Delegate,
2071    ) -> TranslationTranslateCall<'a, C> {
2072        self._delegate = Some(new_value);
2073        self
2074    }
2075
2076    /// Set any additional parameter of the query string used in the request.
2077    /// It should be used to set parameters which are not yet available through their own
2078    /// setters.
2079    ///
2080    /// Please note that this method must not be used to set any of the known parameters
2081    /// which have their own setter method. If done anyway, the request will fail.
2082    ///
2083    /// # Additional Parameters
2084    ///
2085    /// * *$.xgafv* (query-string) - V1 error format.
2086    /// * *access_token* (query-string) - OAuth access token.
2087    /// * *alt* (query-string) - Data format for response.
2088    /// * *bearer_token* (query-string) - OAuth bearer token.
2089    /// * *callback* (query-string) - JSONP
2090    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2091    /// * *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.
2092    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2093    /// * *pp* (query-boolean) - Pretty-print response.
2094    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2095    /// * *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. Overrides userIp if both are provided.
2096    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2097    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2098    pub fn param<T>(mut self, name: T, value: T) -> TranslationTranslateCall<'a, C>
2099    where
2100        T: AsRef<str>,
2101    {
2102        self._additional_params
2103            .insert(name.as_ref().to_string(), value.as_ref().to_string());
2104        self
2105    }
2106
2107    /// Identifies the authorization scope for the method you are building.
2108    ///
2109    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2110    /// [`Scope::CloudPlatform`].
2111    ///
2112    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2113    /// tokens for more than one scope.
2114    ///
2115    /// Usually there is more than one suitable scope to authorize an operation, some of which may
2116    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2117    /// sufficient, a read-write scope will do as well.
2118    pub fn add_scope<St>(mut self, scope: St) -> TranslationTranslateCall<'a, C>
2119    where
2120        St: AsRef<str>,
2121    {
2122        self._scopes.insert(String::from(scope.as_ref()));
2123        self
2124    }
2125    /// Identifies the authorization scope(s) for the method you are building.
2126    ///
2127    /// See [`Self::add_scope()`] for details.
2128    pub fn add_scopes<I, St>(mut self, scopes: I) -> TranslationTranslateCall<'a, C>
2129    where
2130        I: IntoIterator<Item = St>,
2131        St: AsRef<str>,
2132    {
2133        self._scopes
2134            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2135        self
2136    }
2137
2138    /// Removes all scopes, and no default scope will be used either.
2139    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2140    /// for details).
2141    pub fn clear_scopes(mut self) -> TranslationTranslateCall<'a, C> {
2142        self._scopes.clear();
2143        self
2144    }
2145}