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