google_texttospeech1/api.rs
1#![allow(clippy::ptr_arg)]
2
3use std::collections::{BTreeSet, HashMap};
4
5use tokio::time::sleep;
6
7// ##############
8// UTILITIES ###
9// ############
10
11/// Identifies the an OAuth2 authorization scope.
12/// A scope is needed when requesting an
13/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
14#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
15pub enum Scope {
16 /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
17 CloudPlatform,
18}
19
20impl AsRef<str> for Scope {
21 fn as_ref(&self) -> &str {
22 match *self {
23 Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
24 }
25 }
26}
27
28#[allow(clippy::derivable_impls)]
29impl Default for Scope {
30 fn default() -> Scope {
31 Scope::CloudPlatform
32 }
33}
34
35// ########
36// HUB ###
37// ######
38
39/// Central instance to access all Texttospeech related resource activities
40///
41/// # Examples
42///
43/// Instantiate a new hub
44///
45/// ```test_harness,no_run
46/// extern crate hyper;
47/// extern crate hyper_rustls;
48/// extern crate google_texttospeech1 as texttospeech1;
49/// use texttospeech1::api::CancelOperationRequest;
50/// use texttospeech1::{Result, Error};
51/// # async fn dox() {
52/// use texttospeech1::{Texttospeech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
53///
54/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
55/// // `client_secret`, among other things.
56/// let secret: yup_oauth2::ApplicationSecret = Default::default();
57/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
58/// // unless you replace `None` with the desired Flow.
59/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
60/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
61/// // retrieve them from storage.
62/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
63/// .with_native_roots()
64/// .unwrap()
65/// .https_only()
66/// .enable_http2()
67/// .build();
68///
69/// let executor = hyper_util::rt::TokioExecutor::new();
70/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
71/// secret,
72/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
73/// yup_oauth2::client::CustomHyperClientBuilder::from(
74/// hyper_util::client::legacy::Client::builder(executor).build(connector),
75/// ),
76/// ).build().await.unwrap();
77///
78/// let client = hyper_util::client::legacy::Client::builder(
79/// hyper_util::rt::TokioExecutor::new()
80/// )
81/// .build(
82/// hyper_rustls::HttpsConnectorBuilder::new()
83/// .with_native_roots()
84/// .unwrap()
85/// .https_or_http()
86/// .enable_http2()
87/// .build()
88/// );
89/// let mut hub = Texttospeech::new(client, auth);
90/// // As the method needs a request, you would usually fill it with the desired information
91/// // into the respective structure. Some of the parts shown here might not be applicable !
92/// // Values shown here are possibly random and not representative !
93/// let mut req = CancelOperationRequest::default();
94///
95/// // You can configure optional parameters by calling the respective setters at will, and
96/// // execute the final call using `doit()`.
97/// // Values shown here are possibly random and not representative !
98/// let result = hub.operations().cancel(req, "name")
99/// .doit().await;
100///
101/// match result {
102/// Err(e) => match e {
103/// // The Error enum provides details about what exactly happened.
104/// // You can also just use its `Debug`, `Display` or `Error` traits
105/// Error::HttpError(_)
106/// |Error::Io(_)
107/// |Error::MissingAPIKey
108/// |Error::MissingToken(_)
109/// |Error::Cancelled
110/// |Error::UploadSizeLimitExceeded(_, _)
111/// |Error::Failure(_)
112/// |Error::BadRequest(_)
113/// |Error::FieldClash(_)
114/// |Error::JsonDecodeError(_, _) => println!("{}", e),
115/// },
116/// Ok(res) => println!("Success: {:?}", res),
117/// }
118/// # }
119/// ```
120#[derive(Clone)]
121pub struct Texttospeech<C> {
122 pub client: common::Client<C>,
123 pub auth: Box<dyn common::GetToken>,
124 _user_agent: String,
125 _base_url: String,
126 _root_url: String,
127}
128
129impl<C> common::Hub for Texttospeech<C> {}
130
131impl<'a, C> Texttospeech<C> {
132 pub fn new<A: 'static + common::GetToken>(
133 client: common::Client<C>,
134 auth: A,
135 ) -> Texttospeech<C> {
136 Texttospeech {
137 client,
138 auth: Box::new(auth),
139 _user_agent: "google-api-rust-client/7.0.0".to_string(),
140 _base_url: "https://texttospeech.googleapis.com/".to_string(),
141 _root_url: "https://texttospeech.googleapis.com/".to_string(),
142 }
143 }
144
145 pub fn operations(&'a self) -> OperationMethods<'a, C> {
146 OperationMethods { hub: self }
147 }
148 pub fn projects(&'a self) -> ProjectMethods<'a, C> {
149 ProjectMethods { hub: self }
150 }
151 pub fn text(&'a self) -> TextMethods<'a, C> {
152 TextMethods { hub: self }
153 }
154 pub fn voices(&'a self) -> VoiceMethods<'a, C> {
155 VoiceMethods { hub: self }
156 }
157
158 /// Set the user-agent header field to use in all requests to the server.
159 /// It defaults to `google-api-rust-client/7.0.0`.
160 ///
161 /// Returns the previously set user-agent.
162 pub fn user_agent(&mut self, agent_name: String) -> String {
163 std::mem::replace(&mut self._user_agent, agent_name)
164 }
165
166 /// Set the base url to use in all requests to the server.
167 /// It defaults to `https://texttospeech.googleapis.com/`.
168 ///
169 /// Returns the previously set base url.
170 pub fn base_url(&mut self, new_base_url: String) -> String {
171 std::mem::replace(&mut self._base_url, new_base_url)
172 }
173
174 /// Set the root url to use in all requests to the server.
175 /// It defaults to `https://texttospeech.googleapis.com/`.
176 ///
177 /// Returns the previously set root url.
178 pub fn root_url(&mut self, new_root_url: String) -> String {
179 std::mem::replace(&mut self._root_url, new_root_url)
180 }
181}
182
183// ############
184// SCHEMAS ###
185// ##########
186/// Used for advanced voice options.
187///
188/// This type is not used in any activity, and only used as *part* of another schema.
189///
190#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
191#[serde_with::serde_as]
192#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
193pub struct AdvancedVoiceOptions {
194 /// Only for Journey voices. If false, the synthesis is context aware and has a higher latency.
195 #[serde(rename = "lowLatencyJourneySynthesis")]
196 pub low_latency_journey_synthesis: Option<bool>,
197 /// Optional. Input only. If true, relaxes safety filters for Gemini TTS. Only supported for accounts linked to Invoiced (Offline) Cloud billing accounts. Otherwise, will return result google.rpc.Code.INVALID_ARGUMENT.
198 #[serde(rename = "relaxSafetyFilters")]
199 pub relax_safety_filters: Option<bool>,
200}
201
202impl common::Part for AdvancedVoiceOptions {}
203
204/// Description of audio data to be synthesized.
205///
206/// This type is not used in any activity, and only used as *part* of another schema.
207///
208#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
209#[serde_with::serde_as]
210#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
211pub struct AudioConfig {
212 /// Required. The format of the audio byte stream.
213 #[serde(rename = "audioEncoding")]
214 pub audio_encoding: Option<String>,
215 /// Optional. Input only. An identifier which selects 'audio effects' profiles that are applied on (post synthesized) text to speech. Effects are applied on top of each other in the order they are given. See [audio profiles](https://cloud.google.com/text-to-speech/docs/audio-profiles) for current supported profile ids.
216 #[serde(rename = "effectsProfileId")]
217 pub effects_profile_id: Option<Vec<String>>,
218 /// Optional. Input only. Speaking pitch, in the range [-20.0, 20.0]. 20 means increase 20 semitones from the original pitch. -20 means decrease 20 semitones from the original pitch.
219 pub pitch: Option<f64>,
220 /// Optional. The synthesis sample rate (in hertz) for this audio. When this is specified in SynthesizeSpeechRequest, if this is different from the voice's natural sample rate, then the synthesizer will honor this request by converting to the desired sample rate (which might result in worse audio quality), unless the specified sample rate is not supported for the encoding chosen, in which case it will fail the request and return google.rpc.Code.INVALID_ARGUMENT.
221 #[serde(rename = "sampleRateHertz")]
222 pub sample_rate_hertz: Option<i32>,
223 /// Optional. Input only. Speaking rate/speed, in the range [0.25, 2.0]. 1.0 is the normal native speed supported by the specific voice. 2.0 is twice as fast, and 0.5 is half as fast. If unset(0.0), defaults to the native 1.0 speed. Any other values < 0.25 or > 2.0 will return an error.
224 #[serde(rename = "speakingRate")]
225 pub speaking_rate: Option<f64>,
226 /// Optional. Input only. Volume gain (in dB) of the normal native volume supported by the specific voice, in the range [-96.0, 16.0]. If unset, or set to a value of 0.0 (dB), will play at normal native signal amplitude. A value of -6.0 (dB) will play at approximately half the amplitude of the normal native signal amplitude. A value of +6.0 (dB) will play at approximately twice the amplitude of the normal native signal amplitude. Strongly recommend not to exceed +10 (dB) as there's usually no effective increase in loudness for any value greater than that.
227 #[serde(rename = "volumeGainDb")]
228 pub volume_gain_db: Option<f64>,
229}
230
231impl common::Part for AudioConfig {}
232
233/// The request message for Operations.CancelOperation.
234///
235/// # Activities
236///
237/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
238/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
239///
240/// * [cancel operations](OperationCancelCall) (request)
241#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
242#[serde_with::serde_as]
243#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
244pub struct CancelOperationRequest {
245 _never_set: Option<bool>,
246}
247
248impl common::RequestValue for CancelOperationRequest {}
249
250/// Pronunciation customization for a phrase.
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 CustomPronunciationParams {
258 /// The phonetic encoding of the phrase.
259 #[serde(rename = "phoneticEncoding")]
260 pub phonetic_encoding: Option<String>,
261 /// The phrase to which the customization is applied. The phrase can be multiple words, such as proper nouns, but shouldn't span the length of the sentence.
262 pub phrase: Option<String>,
263 /// The pronunciation of the phrase. This must be in the phonetic encoding specified above.
264 pub pronunciation: Option<String>,
265}
266
267impl common::Part for CustomPronunciationParams {}
268
269/// A collection of pronunciation customizations.
270///
271/// This type is not used in any activity, and only used as *part* of another schema.
272///
273#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
274#[serde_with::serde_as]
275#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
276pub struct CustomPronunciations {
277 /// The pronunciation customizations are applied.
278 pub pronunciations: Option<Vec<CustomPronunciationParams>>,
279}
280
281impl common::Part for CustomPronunciations {}
282
283/// Description of the custom voice to be synthesized.
284///
285/// This type is not used in any activity, and only used as *part* of another schema.
286///
287#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
288#[serde_with::serde_as]
289#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
290pub struct CustomVoiceParams {
291 /// Required. The name of the AutoML model that synthesizes the custom voice.
292 pub model: Option<String>,
293 /// Optional. Deprecated. The usage of the synthesized audio to be reported.
294 #[serde(rename = "reportedUsage")]
295 pub reported_usage: Option<String>,
296}
297
298impl common::Part for CustomVoiceParams {}
299
300/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
301///
302/// # Activities
303///
304/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
305/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
306///
307/// * [cancel operations](OperationCancelCall) (response)
308/// * [delete operations](OperationDeleteCall) (response)
309#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
310#[serde_with::serde_as]
311#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
312pub struct Empty {
313 _never_set: Option<bool>,
314}
315
316impl common::ResponseResult for Empty {}
317
318/// The response message for Operations.ListOperations.
319///
320/// # Activities
321///
322/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
323/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
324///
325/// * [locations operations list projects](ProjectLocationOperationListCall) (response)
326#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
327#[serde_with::serde_as]
328#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
329pub struct ListOperationsResponse {
330 /// The standard List next-page token.
331 #[serde(rename = "nextPageToken")]
332 pub next_page_token: Option<String>,
333 /// A list of operations that matches the specified filter in the request.
334 pub operations: Option<Vec<Operation>>,
335 /// Unordered list. Unreachable resources. Populated when the request sets `ListOperationsRequest.return_partial_success` and reads across collections. For example, when attempting to list all resources across all supported locations.
336 pub unreachable: Option<Vec<String>>,
337}
338
339impl common::ResponseResult for ListOperationsResponse {}
340
341/// The message returned to the client by the `ListVoices` method.
342///
343/// # Activities
344///
345/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
346/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
347///
348/// * [list voices](VoiceListCall) (response)
349#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
350#[serde_with::serde_as]
351#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
352pub struct ListVoicesResponse {
353 /// The list of voices.
354 pub voices: Option<Vec<Voice>>,
355}
356
357impl common::ResponseResult for ListVoicesResponse {}
358
359/// A collection of turns for multi-speaker synthesis.
360///
361/// This type is not used in any activity, and only used as *part* of another schema.
362///
363#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
364#[serde_with::serde_as]
365#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
366pub struct MultiSpeakerMarkup {
367 /// Required. Speaker turns.
368 pub turns: Option<Vec<Turn>>,
369}
370
371impl common::Part for MultiSpeakerMarkup {}
372
373/// Configuration for a multi-speaker text-to-speech setup. Enables the use of up to two distinct voices in a single synthesis request.
374///
375/// This type is not used in any activity, and only used as *part* of another schema.
376///
377#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
378#[serde_with::serde_as]
379#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
380pub struct MultiSpeakerVoiceConfig {
381 /// Required. A list of configurations for the voices of the speakers. Exactly two speaker voice configurations must be provided.
382 #[serde(rename = "speakerVoiceConfigs")]
383 pub speaker_voice_configs: Option<Vec<MultispeakerPrebuiltVoice>>,
384}
385
386impl common::Part for MultiSpeakerVoiceConfig {}
387
388/// Configuration for a single speaker in a Gemini TTS multi-speaker setup. Enables dialogue between two speakers.
389///
390/// This type is not used in any activity, and only used as *part* of another schema.
391///
392#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
393#[serde_with::serde_as]
394#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
395pub struct MultispeakerPrebuiltVoice {
396 /// Required. The speaker alias of the voice. This is the user-chosen speaker name that is used in the multispeaker text input, such as "Speaker1".
397 #[serde(rename = "speakerAlias")]
398 pub speaker_alias: Option<String>,
399 /// Required. The speaker ID of the voice. See https://cloud.google.com/text-to-speech/docs/gemini-tts#voice_options for available values.
400 #[serde(rename = "speakerId")]
401 pub speaker_id: Option<String>,
402}
403
404impl common::Part for MultispeakerPrebuiltVoice {}
405
406/// This resource represents a long-running operation that is the result of a network API call.
407///
408/// # Activities
409///
410/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
411/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
412///
413/// * [cancel operations](OperationCancelCall) (none)
414/// * [delete operations](OperationDeleteCall) (none)
415/// * [locations operations get projects](ProjectLocationOperationGetCall) (response)
416/// * [locations synthesize long audio projects](ProjectLocationSynthesizeLongAudioCall) (response)
417#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
418#[serde_with::serde_as]
419#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
420pub struct Operation {
421 /// If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.
422 pub done: Option<bool>,
423 /// The error result of the operation in case of failure or cancellation.
424 pub error: Option<Status>,
425 /// Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
426 pub metadata: Option<HashMap<String, serde_json::Value>>,
427 /// The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.
428 pub name: Option<String>,
429 /// The normal, successful response of the operation. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.
430 pub response: Option<HashMap<String, serde_json::Value>>,
431}
432
433impl common::Resource for Operation {}
434impl common::ResponseResult for Operation {}
435
436/// The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
437///
438/// This type is not used in any activity, and only used as *part* of another schema.
439///
440#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
441#[serde_with::serde_as]
442#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
443pub struct Status {
444 /// The status code, which should be an enum value of google.rpc.Code.
445 pub code: Option<i32>,
446 /// A list of messages that carry the error details. There is a common set of message types for APIs to use.
447 pub details: Option<Vec<HashMap<String, serde_json::Value>>>,
448 /// A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.
449 pub message: Option<String>,
450}
451
452impl common::Part for Status {}
453
454/// Contains text input to be synthesized. Either `text` or `ssml` must be supplied. Supplying both or neither returns google.rpc.Code.INVALID_ARGUMENT. The input size is limited to 5000 bytes.
455///
456/// This type is not used in any activity, and only used as *part* of another schema.
457///
458#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
459#[serde_with::serde_as]
460#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
461pub struct SynthesisInput {
462 /// Optional. The pronunciation customizations are applied to the input. If this is set, the input is synthesized using the given pronunciation customizations. The initial support is for en-us, with plans to expand to other locales in the future. Instant Clone voices aren't supported. In order to customize the pronunciation of a phrase, there must be an exact match of the phrase in the input types. If using SSML, the phrase must not be inside a phoneme tag.
463 #[serde(rename = "customPronunciations")]
464 pub custom_pronunciations: Option<CustomPronunciations>,
465 /// Markup for Chirp 3: HD voices specifically. This field may not be used with any other voices.
466 pub markup: Option<String>,
467 /// The multi-speaker input to be synthesized. Only applicable for multi-speaker synthesis.
468 #[serde(rename = "multiSpeakerMarkup")]
469 pub multi_speaker_markup: Option<MultiSpeakerMarkup>,
470 /// This system instruction is supported only for controllable/promptable voice models. If this system instruction is used, we pass the unedited text to Gemini-TTS. Otherwise, a default system instruction is used. AI Studio calls this system instruction, Style Instructions.
471 pub prompt: Option<String>,
472 /// The SSML document to be synthesized. The SSML document must be valid and well-formed. Otherwise the RPC will fail and return google.rpc.Code.INVALID_ARGUMENT. For more information, see [SSML](https://cloud.google.com/text-to-speech/docs/ssml).
473 pub ssml: Option<String>,
474 /// The raw text to be synthesized.
475 pub text: Option<String>,
476}
477
478impl common::Part for SynthesisInput {}
479
480/// The top-level message sent by the client for the `SynthesizeLongAudio` method.
481///
482/// # Activities
483///
484/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
485/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
486///
487/// * [locations synthesize long audio projects](ProjectLocationSynthesizeLongAudioCall) (request)
488#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
489#[serde_with::serde_as]
490#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
491pub struct SynthesizeLongAudioRequest {
492 /// Required. The configuration of the synthesized audio.
493 #[serde(rename = "audioConfig")]
494 pub audio_config: Option<AudioConfig>,
495 /// Required. The Synthesizer requires either plain text or SSML as input.
496 pub input: Option<SynthesisInput>,
497 /// Required. Specifies a Cloud Storage URI for the synthesis results. Must be specified in the format: `gs://bucket_name/object_name`, and the bucket must already exist.
498 #[serde(rename = "outputGcsUri")]
499 pub output_gcs_uri: Option<String>,
500 /// Required. The desired voice of the synthesized audio.
501 pub voice: Option<VoiceSelectionParams>,
502}
503
504impl common::RequestValue for SynthesizeLongAudioRequest {}
505
506/// The top-level message sent by the client for the `SynthesizeSpeech` method.
507///
508/// # Activities
509///
510/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
511/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
512///
513/// * [synthesize text](TextSynthesizeCall) (request)
514#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
515#[serde_with::serde_as]
516#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
517pub struct SynthesizeSpeechRequest {
518 /// Advanced voice options.
519 #[serde(rename = "advancedVoiceOptions")]
520 pub advanced_voice_options: Option<AdvancedVoiceOptions>,
521 /// Required. The configuration of the synthesized audio.
522 #[serde(rename = "audioConfig")]
523 pub audio_config: Option<AudioConfig>,
524 /// Required. The Synthesizer requires either plain text or SSML as input.
525 pub input: Option<SynthesisInput>,
526 /// Required. The desired voice of the synthesized audio.
527 pub voice: Option<VoiceSelectionParams>,
528}
529
530impl common::RequestValue for SynthesizeSpeechRequest {}
531
532/// The message returned to the client by the `SynthesizeSpeech` method.
533///
534/// # Activities
535///
536/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
537/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
538///
539/// * [synthesize text](TextSynthesizeCall) (response)
540#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
541#[serde_with::serde_as]
542#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
543pub struct SynthesizeSpeechResponse {
544 /// The audio data bytes encoded as specified in the request, including the header for encodings that are wrapped in containers (e.g. MP3, OGG_OPUS). For LINEAR16 audio, we include the WAV header. Note: as with all bytes fields, protobuffers use a pure binary representation, whereas JSON representations use base64.
545 #[serde(rename = "audioContent")]
546 #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
547 pub audio_content: Option<Vec<u8>>,
548}
549
550impl common::ResponseResult for SynthesizeSpeechResponse {}
551
552/// A multi-speaker turn.
553///
554/// This type is not used in any activity, and only used as *part* of another schema.
555///
556#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
557#[serde_with::serde_as]
558#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
559pub struct Turn {
560 /// Required. The speaker of the turn, for example, 'O' or 'Q'. Please refer to documentation for available speakers.
561 pub speaker: Option<String>,
562 /// Required. The text to speak.
563 pub text: Option<String>,
564}
565
566impl common::Part for Turn {}
567
568/// Description of a voice supported by the TTS service.
569///
570/// # Activities
571///
572/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
573/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
574///
575/// * [list voices](VoiceListCall) (none)
576#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
577#[serde_with::serde_as]
578#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
579pub struct Voice {
580 /// The languages that this voice supports, expressed as [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tags (e.g. "en-US", "es-419", "cmn-tw").
581 #[serde(rename = "languageCodes")]
582 pub language_codes: Option<Vec<String>>,
583 /// The name of this voice. Each distinct voice has a unique name.
584 pub name: Option<String>,
585 /// The natural sample rate (in hertz) for this voice.
586 #[serde(rename = "naturalSampleRateHertz")]
587 pub natural_sample_rate_hertz: Option<i32>,
588 /// The gender of this voice.
589 #[serde(rename = "ssmlGender")]
590 pub ssml_gender: Option<String>,
591}
592
593impl common::Resource for Voice {}
594
595/// The configuration of Voice Clone feature.
596///
597/// This type is not used in any activity, and only used as *part* of another schema.
598///
599#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
600#[serde_with::serde_as]
601#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
602pub struct VoiceCloneParams {
603 /// Required. Created by GenerateVoiceCloningKey.
604 #[serde(rename = "voiceCloningKey")]
605 pub voice_cloning_key: Option<String>,
606}
607
608impl common::Part for VoiceCloneParams {}
609
610/// Description of which voice to use for a synthesis request.
611///
612/// This type is not used in any activity, and only used as *part* of another schema.
613///
614#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
615#[serde_with::serde_as]
616#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
617pub struct VoiceSelectionParams {
618 /// The configuration for a custom voice. If [CustomVoiceParams.model] is set, the service will choose the custom voice matching the specified configuration.
619 #[serde(rename = "customVoice")]
620 pub custom_voice: Option<CustomVoiceParams>,
621 /// Required. The language (and potentially also the region) of the voice expressed as a [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag, e.g. "en-US". This should not include a script tag (e.g. use "cmn-cn" rather than "cmn-Hant-cn"), because the script will be inferred from the input provided in the SynthesisInput. The TTS service will use this parameter to help choose an appropriate voice. Note that the TTS service may choose a voice with a slightly different language code than the one selected; it may substitute a different region (e.g. using en-US rather than en-CA if there isn't a Canadian voice available), or even a different language, e.g. using "nb" (Norwegian Bokmal) instead of "no" (Norwegian)".
622 #[serde(rename = "languageCode")]
623 pub language_code: Option<String>,
624 /// Optional. The name of the model. If set, the service will choose the model matching the specified configuration.
625 #[serde(rename = "modelName")]
626 pub model_name: Option<String>,
627 /// Optional. The configuration for a Gemini multi-speaker text-to-speech setup. Enables the use of two distinct voices in a single synthesis request.
628 #[serde(rename = "multiSpeakerVoiceConfig")]
629 pub multi_speaker_voice_config: Option<MultiSpeakerVoiceConfig>,
630 /// The name of the voice. If both the name and the gender are not set, the service will choose a voice based on the other parameters such as language_code.
631 pub name: Option<String>,
632 /// The preferred gender of the voice. If not set, the service will choose a voice based on the other parameters such as language_code and name. Note that this is only a preference, not requirement; if a voice of the appropriate gender is not available, the synthesizer should substitute a voice with a different gender rather than failing the request.
633 #[serde(rename = "ssmlGender")]
634 pub ssml_gender: Option<String>,
635 /// Optional. The configuration for a voice clone. If [VoiceCloneParams.voice_clone_key] is set, the service chooses the voice clone matching the specified configuration.
636 #[serde(rename = "voiceClone")]
637 pub voice_clone: Option<VoiceCloneParams>,
638}
639
640impl common::Part for VoiceSelectionParams {}
641
642// ###################
643// MethodBuilders ###
644// #################
645
646/// A builder providing access to all methods supported on *operation* resources.
647/// It is not used directly, but through the [`Texttospeech`] hub.
648///
649/// # Example
650///
651/// Instantiate a resource builder
652///
653/// ```test_harness,no_run
654/// extern crate hyper;
655/// extern crate hyper_rustls;
656/// extern crate google_texttospeech1 as texttospeech1;
657///
658/// # async fn dox() {
659/// use texttospeech1::{Texttospeech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
660///
661/// let secret: yup_oauth2::ApplicationSecret = Default::default();
662/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
663/// .with_native_roots()
664/// .unwrap()
665/// .https_only()
666/// .enable_http2()
667/// .build();
668///
669/// let executor = hyper_util::rt::TokioExecutor::new();
670/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
671/// secret,
672/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
673/// yup_oauth2::client::CustomHyperClientBuilder::from(
674/// hyper_util::client::legacy::Client::builder(executor).build(connector),
675/// ),
676/// ).build().await.unwrap();
677///
678/// let client = hyper_util::client::legacy::Client::builder(
679/// hyper_util::rt::TokioExecutor::new()
680/// )
681/// .build(
682/// hyper_rustls::HttpsConnectorBuilder::new()
683/// .with_native_roots()
684/// .unwrap()
685/// .https_or_http()
686/// .enable_http2()
687/// .build()
688/// );
689/// let mut hub = Texttospeech::new(client, auth);
690/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
691/// // like `cancel(...)` and `delete(...)`
692/// // to build up your call.
693/// let rb = hub.operations();
694/// # }
695/// ```
696pub struct OperationMethods<'a, C>
697where
698 C: 'a,
699{
700 hub: &'a Texttospeech<C>,
701}
702
703impl<'a, C> common::MethodsBuilder for OperationMethods<'a, C> {}
704
705impl<'a, C> OperationMethods<'a, C> {
706 /// Create a builder to help you perform the following task:
707 ///
708 /// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of `1`, corresponding to `Code.CANCELLED`.
709 ///
710 /// # Arguments
711 ///
712 /// * `request` - No description provided.
713 /// * `name` - The name of the operation resource to be cancelled.
714 pub fn cancel(
715 &self,
716 request: CancelOperationRequest,
717 name: &str,
718 ) -> OperationCancelCall<'a, C> {
719 OperationCancelCall {
720 hub: self.hub,
721 _request: request,
722 _name: name.to_string(),
723 _delegate: Default::default(),
724 _additional_params: Default::default(),
725 _scopes: Default::default(),
726 }
727 }
728
729 /// Create a builder to help you perform the following task:
730 ///
731 /// Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`.
732 ///
733 /// # Arguments
734 ///
735 /// * `name` - The name of the operation resource to be deleted.
736 pub fn delete(&self, name: &str) -> OperationDeleteCall<'a, C> {
737 OperationDeleteCall {
738 hub: self.hub,
739 _name: name.to_string(),
740 _delegate: Default::default(),
741 _additional_params: Default::default(),
742 _scopes: Default::default(),
743 }
744 }
745}
746
747/// A builder providing access to all methods supported on *project* resources.
748/// It is not used directly, but through the [`Texttospeech`] hub.
749///
750/// # Example
751///
752/// Instantiate a resource builder
753///
754/// ```test_harness,no_run
755/// extern crate hyper;
756/// extern crate hyper_rustls;
757/// extern crate google_texttospeech1 as texttospeech1;
758///
759/// # async fn dox() {
760/// use texttospeech1::{Texttospeech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
761///
762/// let secret: yup_oauth2::ApplicationSecret = Default::default();
763/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
764/// .with_native_roots()
765/// .unwrap()
766/// .https_only()
767/// .enable_http2()
768/// .build();
769///
770/// let executor = hyper_util::rt::TokioExecutor::new();
771/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
772/// secret,
773/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
774/// yup_oauth2::client::CustomHyperClientBuilder::from(
775/// hyper_util::client::legacy::Client::builder(executor).build(connector),
776/// ),
777/// ).build().await.unwrap();
778///
779/// let client = hyper_util::client::legacy::Client::builder(
780/// hyper_util::rt::TokioExecutor::new()
781/// )
782/// .build(
783/// hyper_rustls::HttpsConnectorBuilder::new()
784/// .with_native_roots()
785/// .unwrap()
786/// .https_or_http()
787/// .enable_http2()
788/// .build()
789/// );
790/// let mut hub = Texttospeech::new(client, auth);
791/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
792/// // like `locations_operations_get(...)`, `locations_operations_list(...)` and `locations_synthesize_long_audio(...)`
793/// // to build up your call.
794/// let rb = hub.projects();
795/// # }
796/// ```
797pub struct ProjectMethods<'a, C>
798where
799 C: 'a,
800{
801 hub: &'a Texttospeech<C>,
802}
803
804impl<'a, C> common::MethodsBuilder for ProjectMethods<'a, C> {}
805
806impl<'a, C> ProjectMethods<'a, C> {
807 /// Create a builder to help you perform the following task:
808 ///
809 /// Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
810 ///
811 /// # Arguments
812 ///
813 /// * `name` - The name of the operation resource.
814 pub fn locations_operations_get(&self, name: &str) -> ProjectLocationOperationGetCall<'a, C> {
815 ProjectLocationOperationGetCall {
816 hub: self.hub,
817 _name: name.to_string(),
818 _delegate: Default::default(),
819 _additional_params: Default::default(),
820 _scopes: Default::default(),
821 }
822 }
823
824 /// Create a builder to help you perform the following task:
825 ///
826 /// Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`.
827 ///
828 /// # Arguments
829 ///
830 /// * `name` - The name of the operation's parent resource.
831 pub fn locations_operations_list(&self, name: &str) -> ProjectLocationOperationListCall<'a, C> {
832 ProjectLocationOperationListCall {
833 hub: self.hub,
834 _name: name.to_string(),
835 _return_partial_success: Default::default(),
836 _page_token: Default::default(),
837 _page_size: Default::default(),
838 _filter: Default::default(),
839 _delegate: Default::default(),
840 _additional_params: Default::default(),
841 _scopes: Default::default(),
842 }
843 }
844
845 /// Create a builder to help you perform the following task:
846 ///
847 /// Synthesizes long form text asynchronously.
848 ///
849 /// # Arguments
850 ///
851 /// * `request` - No description provided.
852 /// * `parent` - The resource states of the request in the form of `projects/*/locations/*`.
853 pub fn locations_synthesize_long_audio(
854 &self,
855 request: SynthesizeLongAudioRequest,
856 parent: &str,
857 ) -> ProjectLocationSynthesizeLongAudioCall<'a, C> {
858 ProjectLocationSynthesizeLongAudioCall {
859 hub: self.hub,
860 _request: request,
861 _parent: parent.to_string(),
862 _delegate: Default::default(),
863 _additional_params: Default::default(),
864 _scopes: Default::default(),
865 }
866 }
867}
868
869/// A builder providing access to all methods supported on *text* resources.
870/// It is not used directly, but through the [`Texttospeech`] hub.
871///
872/// # Example
873///
874/// Instantiate a resource builder
875///
876/// ```test_harness,no_run
877/// extern crate hyper;
878/// extern crate hyper_rustls;
879/// extern crate google_texttospeech1 as texttospeech1;
880///
881/// # async fn dox() {
882/// use texttospeech1::{Texttospeech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
883///
884/// let secret: yup_oauth2::ApplicationSecret = Default::default();
885/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
886/// .with_native_roots()
887/// .unwrap()
888/// .https_only()
889/// .enable_http2()
890/// .build();
891///
892/// let executor = hyper_util::rt::TokioExecutor::new();
893/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
894/// secret,
895/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
896/// yup_oauth2::client::CustomHyperClientBuilder::from(
897/// hyper_util::client::legacy::Client::builder(executor).build(connector),
898/// ),
899/// ).build().await.unwrap();
900///
901/// let client = hyper_util::client::legacy::Client::builder(
902/// hyper_util::rt::TokioExecutor::new()
903/// )
904/// .build(
905/// hyper_rustls::HttpsConnectorBuilder::new()
906/// .with_native_roots()
907/// .unwrap()
908/// .https_or_http()
909/// .enable_http2()
910/// .build()
911/// );
912/// let mut hub = Texttospeech::new(client, auth);
913/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
914/// // like `synthesize(...)`
915/// // to build up your call.
916/// let rb = hub.text();
917/// # }
918/// ```
919pub struct TextMethods<'a, C>
920where
921 C: 'a,
922{
923 hub: &'a Texttospeech<C>,
924}
925
926impl<'a, C> common::MethodsBuilder for TextMethods<'a, C> {}
927
928impl<'a, C> TextMethods<'a, C> {
929 /// Create a builder to help you perform the following task:
930 ///
931 /// Synthesizes speech synchronously: receive results after all text input has been processed.
932 ///
933 /// # Arguments
934 ///
935 /// * `request` - No description provided.
936 pub fn synthesize(&self, request: SynthesizeSpeechRequest) -> TextSynthesizeCall<'a, C> {
937 TextSynthesizeCall {
938 hub: self.hub,
939 _request: request,
940 _delegate: Default::default(),
941 _additional_params: Default::default(),
942 _scopes: Default::default(),
943 }
944 }
945}
946
947/// A builder providing access to all methods supported on *voice* resources.
948/// It is not used directly, but through the [`Texttospeech`] hub.
949///
950/// # Example
951///
952/// Instantiate a resource builder
953///
954/// ```test_harness,no_run
955/// extern crate hyper;
956/// extern crate hyper_rustls;
957/// extern crate google_texttospeech1 as texttospeech1;
958///
959/// # async fn dox() {
960/// use texttospeech1::{Texttospeech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
961///
962/// let secret: yup_oauth2::ApplicationSecret = Default::default();
963/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
964/// .with_native_roots()
965/// .unwrap()
966/// .https_only()
967/// .enable_http2()
968/// .build();
969///
970/// let executor = hyper_util::rt::TokioExecutor::new();
971/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
972/// secret,
973/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
974/// yup_oauth2::client::CustomHyperClientBuilder::from(
975/// hyper_util::client::legacy::Client::builder(executor).build(connector),
976/// ),
977/// ).build().await.unwrap();
978///
979/// let client = hyper_util::client::legacy::Client::builder(
980/// hyper_util::rt::TokioExecutor::new()
981/// )
982/// .build(
983/// hyper_rustls::HttpsConnectorBuilder::new()
984/// .with_native_roots()
985/// .unwrap()
986/// .https_or_http()
987/// .enable_http2()
988/// .build()
989/// );
990/// let mut hub = Texttospeech::new(client, auth);
991/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
992/// // like `list(...)`
993/// // to build up your call.
994/// let rb = hub.voices();
995/// # }
996/// ```
997pub struct VoiceMethods<'a, C>
998where
999 C: 'a,
1000{
1001 hub: &'a Texttospeech<C>,
1002}
1003
1004impl<'a, C> common::MethodsBuilder for VoiceMethods<'a, C> {}
1005
1006impl<'a, C> VoiceMethods<'a, C> {
1007 /// Create a builder to help you perform the following task:
1008 ///
1009 /// Returns a list of Voice supported for synthesis.
1010 pub fn list(&self) -> VoiceListCall<'a, C> {
1011 VoiceListCall {
1012 hub: self.hub,
1013 _language_code: Default::default(),
1014 _delegate: Default::default(),
1015 _additional_params: Default::default(),
1016 _scopes: Default::default(),
1017 }
1018 }
1019}
1020
1021// ###################
1022// CallBuilders ###
1023// #################
1024
1025/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of `1`, corresponding to `Code.CANCELLED`.
1026///
1027/// A builder for the *cancel* method supported by a *operation* resource.
1028/// It is not used directly, but through a [`OperationMethods`] instance.
1029///
1030/// # Example
1031///
1032/// Instantiate a resource method builder
1033///
1034/// ```test_harness,no_run
1035/// # extern crate hyper;
1036/// # extern crate hyper_rustls;
1037/// # extern crate google_texttospeech1 as texttospeech1;
1038/// use texttospeech1::api::CancelOperationRequest;
1039/// # async fn dox() {
1040/// # use texttospeech1::{Texttospeech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1041///
1042/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1043/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1044/// # .with_native_roots()
1045/// # .unwrap()
1046/// # .https_only()
1047/// # .enable_http2()
1048/// # .build();
1049///
1050/// # let executor = hyper_util::rt::TokioExecutor::new();
1051/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1052/// # secret,
1053/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1054/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1055/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1056/// # ),
1057/// # ).build().await.unwrap();
1058///
1059/// # let client = hyper_util::client::legacy::Client::builder(
1060/// # hyper_util::rt::TokioExecutor::new()
1061/// # )
1062/// # .build(
1063/// # hyper_rustls::HttpsConnectorBuilder::new()
1064/// # .with_native_roots()
1065/// # .unwrap()
1066/// # .https_or_http()
1067/// # .enable_http2()
1068/// # .build()
1069/// # );
1070/// # let mut hub = Texttospeech::new(client, auth);
1071/// // As the method needs a request, you would usually fill it with the desired information
1072/// // into the respective structure. Some of the parts shown here might not be applicable !
1073/// // Values shown here are possibly random and not representative !
1074/// let mut req = CancelOperationRequest::default();
1075///
1076/// // You can configure optional parameters by calling the respective setters at will, and
1077/// // execute the final call using `doit()`.
1078/// // Values shown here are possibly random and not representative !
1079/// let result = hub.operations().cancel(req, "name")
1080/// .doit().await;
1081/// # }
1082/// ```
1083pub struct OperationCancelCall<'a, C>
1084where
1085 C: 'a,
1086{
1087 hub: &'a Texttospeech<C>,
1088 _request: CancelOperationRequest,
1089 _name: String,
1090 _delegate: Option<&'a mut dyn common::Delegate>,
1091 _additional_params: HashMap<String, String>,
1092 _scopes: BTreeSet<String>,
1093}
1094
1095impl<'a, C> common::CallBuilder for OperationCancelCall<'a, C> {}
1096
1097impl<'a, C> OperationCancelCall<'a, C>
1098where
1099 C: common::Connector,
1100{
1101 /// Perform the operation you have build so far.
1102 pub async fn doit(mut self) -> common::Result<(common::Response, Empty)> {
1103 use std::borrow::Cow;
1104 use std::io::{Read, Seek};
1105
1106 use common::{url::Params, ToParts};
1107 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1108
1109 let mut dd = common::DefaultDelegate;
1110 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1111 dlg.begin(common::MethodInfo {
1112 id: "texttospeech.operations.cancel",
1113 http_method: hyper::Method::POST,
1114 });
1115
1116 for &field in ["alt", "name"].iter() {
1117 if self._additional_params.contains_key(field) {
1118 dlg.finished(false);
1119 return Err(common::Error::FieldClash(field));
1120 }
1121 }
1122
1123 let mut params = Params::with_capacity(4 + self._additional_params.len());
1124 params.push("name", self._name);
1125
1126 params.extend(self._additional_params.iter());
1127
1128 params.push("alt", "json");
1129 let mut url = self.hub._base_url.clone() + "v1/{+name}:cancel";
1130 if self._scopes.is_empty() {
1131 self._scopes
1132 .insert(Scope::CloudPlatform.as_ref().to_string());
1133 }
1134
1135 #[allow(clippy::single_element_loop)]
1136 for &(find_this, param_name) in [("{+name}", "name")].iter() {
1137 url = params.uri_replacement(url, param_name, find_this, true);
1138 }
1139 {
1140 let to_remove = ["name"];
1141 params.remove_params(&to_remove);
1142 }
1143
1144 let url = params.parse_with_url(&url);
1145
1146 let mut json_mime_type = mime::APPLICATION_JSON;
1147 let mut request_value_reader = {
1148 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1149 common::remove_json_null_values(&mut value);
1150 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1151 serde_json::to_writer(&mut dst, &value).unwrap();
1152 dst
1153 };
1154 let request_size = request_value_reader
1155 .seek(std::io::SeekFrom::End(0))
1156 .unwrap();
1157 request_value_reader
1158 .seek(std::io::SeekFrom::Start(0))
1159 .unwrap();
1160
1161 loop {
1162 let token = match self
1163 .hub
1164 .auth
1165 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1166 .await
1167 {
1168 Ok(token) => token,
1169 Err(e) => match dlg.token(e) {
1170 Ok(token) => token,
1171 Err(e) => {
1172 dlg.finished(false);
1173 return Err(common::Error::MissingToken(e));
1174 }
1175 },
1176 };
1177 request_value_reader
1178 .seek(std::io::SeekFrom::Start(0))
1179 .unwrap();
1180 let mut req_result = {
1181 let client = &self.hub.client;
1182 dlg.pre_request();
1183 let mut req_builder = hyper::Request::builder()
1184 .method(hyper::Method::POST)
1185 .uri(url.as_str())
1186 .header(USER_AGENT, self.hub._user_agent.clone());
1187
1188 if let Some(token) = token.as_ref() {
1189 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1190 }
1191
1192 let request = req_builder
1193 .header(CONTENT_TYPE, json_mime_type.to_string())
1194 .header(CONTENT_LENGTH, request_size as u64)
1195 .body(common::to_body(
1196 request_value_reader.get_ref().clone().into(),
1197 ));
1198
1199 client.request(request.unwrap()).await
1200 };
1201
1202 match req_result {
1203 Err(err) => {
1204 if let common::Retry::After(d) = dlg.http_error(&err) {
1205 sleep(d).await;
1206 continue;
1207 }
1208 dlg.finished(false);
1209 return Err(common::Error::HttpError(err));
1210 }
1211 Ok(res) => {
1212 let (mut parts, body) = res.into_parts();
1213 let mut body = common::Body::new(body);
1214 if !parts.status.is_success() {
1215 let bytes = common::to_bytes(body).await.unwrap_or_default();
1216 let error = serde_json::from_str(&common::to_string(&bytes));
1217 let response = common::to_response(parts, bytes.into());
1218
1219 if let common::Retry::After(d) =
1220 dlg.http_failure(&response, error.as_ref().ok())
1221 {
1222 sleep(d).await;
1223 continue;
1224 }
1225
1226 dlg.finished(false);
1227
1228 return Err(match error {
1229 Ok(value) => common::Error::BadRequest(value),
1230 _ => common::Error::Failure(response),
1231 });
1232 }
1233 let response = {
1234 let bytes = common::to_bytes(body).await.unwrap_or_default();
1235 let encoded = common::to_string(&bytes);
1236 match serde_json::from_str(&encoded) {
1237 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1238 Err(error) => {
1239 dlg.response_json_decode_error(&encoded, &error);
1240 return Err(common::Error::JsonDecodeError(
1241 encoded.to_string(),
1242 error,
1243 ));
1244 }
1245 }
1246 };
1247
1248 dlg.finished(true);
1249 return Ok(response);
1250 }
1251 }
1252 }
1253 }
1254
1255 ///
1256 /// Sets the *request* property to the given value.
1257 ///
1258 /// Even though the property as already been set when instantiating this call,
1259 /// we provide this method for API completeness.
1260 pub fn request(mut self, new_value: CancelOperationRequest) -> OperationCancelCall<'a, C> {
1261 self._request = new_value;
1262 self
1263 }
1264 /// The name of the operation resource to be cancelled.
1265 ///
1266 /// Sets the *name* path property to the given value.
1267 ///
1268 /// Even though the property as already been set when instantiating this call,
1269 /// we provide this method for API completeness.
1270 pub fn name(mut self, new_value: &str) -> OperationCancelCall<'a, C> {
1271 self._name = new_value.to_string();
1272 self
1273 }
1274 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1275 /// while executing the actual API request.
1276 ///
1277 /// ````text
1278 /// It should be used to handle progress information, and to implement a certain level of resilience.
1279 /// ````
1280 ///
1281 /// Sets the *delegate* property to the given value.
1282 pub fn delegate(
1283 mut self,
1284 new_value: &'a mut dyn common::Delegate,
1285 ) -> OperationCancelCall<'a, C> {
1286 self._delegate = Some(new_value);
1287 self
1288 }
1289
1290 /// Set any additional parameter of the query string used in the request.
1291 /// It should be used to set parameters which are not yet available through their own
1292 /// setters.
1293 ///
1294 /// Please note that this method must not be used to set any of the known parameters
1295 /// which have their own setter method. If done anyway, the request will fail.
1296 ///
1297 /// # Additional Parameters
1298 ///
1299 /// * *$.xgafv* (query-string) - V1 error format.
1300 /// * *access_token* (query-string) - OAuth access token.
1301 /// * *alt* (query-string) - Data format for response.
1302 /// * *callback* (query-string) - JSONP
1303 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1304 /// * *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.
1305 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1306 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1307 /// * *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.
1308 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1309 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1310 pub fn param<T>(mut self, name: T, value: T) -> OperationCancelCall<'a, C>
1311 where
1312 T: AsRef<str>,
1313 {
1314 self._additional_params
1315 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1316 self
1317 }
1318
1319 /// Identifies the authorization scope for the method you are building.
1320 ///
1321 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1322 /// [`Scope::CloudPlatform`].
1323 ///
1324 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1325 /// tokens for more than one scope.
1326 ///
1327 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1328 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1329 /// sufficient, a read-write scope will do as well.
1330 pub fn add_scope<St>(mut self, scope: St) -> OperationCancelCall<'a, C>
1331 where
1332 St: AsRef<str>,
1333 {
1334 self._scopes.insert(String::from(scope.as_ref()));
1335 self
1336 }
1337 /// Identifies the authorization scope(s) for the method you are building.
1338 ///
1339 /// See [`Self::add_scope()`] for details.
1340 pub fn add_scopes<I, St>(mut self, scopes: I) -> OperationCancelCall<'a, C>
1341 where
1342 I: IntoIterator<Item = St>,
1343 St: AsRef<str>,
1344 {
1345 self._scopes
1346 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1347 self
1348 }
1349
1350 /// Removes all scopes, and no default scope will be used either.
1351 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1352 /// for details).
1353 pub fn clear_scopes(mut self) -> OperationCancelCall<'a, C> {
1354 self._scopes.clear();
1355 self
1356 }
1357}
1358
1359/// Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`.
1360///
1361/// A builder for the *delete* method supported by a *operation* resource.
1362/// It is not used directly, but through a [`OperationMethods`] instance.
1363///
1364/// # Example
1365///
1366/// Instantiate a resource method builder
1367///
1368/// ```test_harness,no_run
1369/// # extern crate hyper;
1370/// # extern crate hyper_rustls;
1371/// # extern crate google_texttospeech1 as texttospeech1;
1372/// # async fn dox() {
1373/// # use texttospeech1::{Texttospeech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1374///
1375/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1376/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1377/// # .with_native_roots()
1378/// # .unwrap()
1379/// # .https_only()
1380/// # .enable_http2()
1381/// # .build();
1382///
1383/// # let executor = hyper_util::rt::TokioExecutor::new();
1384/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1385/// # secret,
1386/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1387/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1388/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1389/// # ),
1390/// # ).build().await.unwrap();
1391///
1392/// # let client = hyper_util::client::legacy::Client::builder(
1393/// # hyper_util::rt::TokioExecutor::new()
1394/// # )
1395/// # .build(
1396/// # hyper_rustls::HttpsConnectorBuilder::new()
1397/// # .with_native_roots()
1398/// # .unwrap()
1399/// # .https_or_http()
1400/// # .enable_http2()
1401/// # .build()
1402/// # );
1403/// # let mut hub = Texttospeech::new(client, auth);
1404/// // You can configure optional parameters by calling the respective setters at will, and
1405/// // execute the final call using `doit()`.
1406/// // Values shown here are possibly random and not representative !
1407/// let result = hub.operations().delete("name")
1408/// .doit().await;
1409/// # }
1410/// ```
1411pub struct OperationDeleteCall<'a, C>
1412where
1413 C: 'a,
1414{
1415 hub: &'a Texttospeech<C>,
1416 _name: String,
1417 _delegate: Option<&'a mut dyn common::Delegate>,
1418 _additional_params: HashMap<String, String>,
1419 _scopes: BTreeSet<String>,
1420}
1421
1422impl<'a, C> common::CallBuilder for OperationDeleteCall<'a, C> {}
1423
1424impl<'a, C> OperationDeleteCall<'a, C>
1425where
1426 C: common::Connector,
1427{
1428 /// Perform the operation you have build so far.
1429 pub async fn doit(mut self) -> common::Result<(common::Response, Empty)> {
1430 use std::borrow::Cow;
1431 use std::io::{Read, Seek};
1432
1433 use common::{url::Params, ToParts};
1434 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1435
1436 let mut dd = common::DefaultDelegate;
1437 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1438 dlg.begin(common::MethodInfo {
1439 id: "texttospeech.operations.delete",
1440 http_method: hyper::Method::DELETE,
1441 });
1442
1443 for &field in ["alt", "name"].iter() {
1444 if self._additional_params.contains_key(field) {
1445 dlg.finished(false);
1446 return Err(common::Error::FieldClash(field));
1447 }
1448 }
1449
1450 let mut params = Params::with_capacity(3 + self._additional_params.len());
1451 params.push("name", self._name);
1452
1453 params.extend(self._additional_params.iter());
1454
1455 params.push("alt", "json");
1456 let mut url = self.hub._base_url.clone() + "v1/{+name}";
1457 if self._scopes.is_empty() {
1458 self._scopes
1459 .insert(Scope::CloudPlatform.as_ref().to_string());
1460 }
1461
1462 #[allow(clippy::single_element_loop)]
1463 for &(find_this, param_name) in [("{+name}", "name")].iter() {
1464 url = params.uri_replacement(url, param_name, find_this, true);
1465 }
1466 {
1467 let to_remove = ["name"];
1468 params.remove_params(&to_remove);
1469 }
1470
1471 let url = params.parse_with_url(&url);
1472
1473 loop {
1474 let token = match self
1475 .hub
1476 .auth
1477 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1478 .await
1479 {
1480 Ok(token) => token,
1481 Err(e) => match dlg.token(e) {
1482 Ok(token) => token,
1483 Err(e) => {
1484 dlg.finished(false);
1485 return Err(common::Error::MissingToken(e));
1486 }
1487 },
1488 };
1489 let mut req_result = {
1490 let client = &self.hub.client;
1491 dlg.pre_request();
1492 let mut req_builder = hyper::Request::builder()
1493 .method(hyper::Method::DELETE)
1494 .uri(url.as_str())
1495 .header(USER_AGENT, self.hub._user_agent.clone());
1496
1497 if let Some(token) = token.as_ref() {
1498 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1499 }
1500
1501 let request = req_builder
1502 .header(CONTENT_LENGTH, 0_u64)
1503 .body(common::to_body::<String>(None));
1504
1505 client.request(request.unwrap()).await
1506 };
1507
1508 match req_result {
1509 Err(err) => {
1510 if let common::Retry::After(d) = dlg.http_error(&err) {
1511 sleep(d).await;
1512 continue;
1513 }
1514 dlg.finished(false);
1515 return Err(common::Error::HttpError(err));
1516 }
1517 Ok(res) => {
1518 let (mut parts, body) = res.into_parts();
1519 let mut body = common::Body::new(body);
1520 if !parts.status.is_success() {
1521 let bytes = common::to_bytes(body).await.unwrap_or_default();
1522 let error = serde_json::from_str(&common::to_string(&bytes));
1523 let response = common::to_response(parts, bytes.into());
1524
1525 if let common::Retry::After(d) =
1526 dlg.http_failure(&response, error.as_ref().ok())
1527 {
1528 sleep(d).await;
1529 continue;
1530 }
1531
1532 dlg.finished(false);
1533
1534 return Err(match error {
1535 Ok(value) => common::Error::BadRequest(value),
1536 _ => common::Error::Failure(response),
1537 });
1538 }
1539 let response = {
1540 let bytes = common::to_bytes(body).await.unwrap_or_default();
1541 let encoded = common::to_string(&bytes);
1542 match serde_json::from_str(&encoded) {
1543 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1544 Err(error) => {
1545 dlg.response_json_decode_error(&encoded, &error);
1546 return Err(common::Error::JsonDecodeError(
1547 encoded.to_string(),
1548 error,
1549 ));
1550 }
1551 }
1552 };
1553
1554 dlg.finished(true);
1555 return Ok(response);
1556 }
1557 }
1558 }
1559 }
1560
1561 /// The name of the operation resource to be deleted.
1562 ///
1563 /// Sets the *name* path property to the given value.
1564 ///
1565 /// Even though the property as already been set when instantiating this call,
1566 /// we provide this method for API completeness.
1567 pub fn name(mut self, new_value: &str) -> OperationDeleteCall<'a, C> {
1568 self._name = new_value.to_string();
1569 self
1570 }
1571 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1572 /// while executing the actual API request.
1573 ///
1574 /// ````text
1575 /// It should be used to handle progress information, and to implement a certain level of resilience.
1576 /// ````
1577 ///
1578 /// Sets the *delegate* property to the given value.
1579 pub fn delegate(
1580 mut self,
1581 new_value: &'a mut dyn common::Delegate,
1582 ) -> OperationDeleteCall<'a, C> {
1583 self._delegate = Some(new_value);
1584 self
1585 }
1586
1587 /// Set any additional parameter of the query string used in the request.
1588 /// It should be used to set parameters which are not yet available through their own
1589 /// setters.
1590 ///
1591 /// Please note that this method must not be used to set any of the known parameters
1592 /// which have their own setter method. If done anyway, the request will fail.
1593 ///
1594 /// # Additional Parameters
1595 ///
1596 /// * *$.xgafv* (query-string) - V1 error format.
1597 /// * *access_token* (query-string) - OAuth access token.
1598 /// * *alt* (query-string) - Data format for response.
1599 /// * *callback* (query-string) - JSONP
1600 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1601 /// * *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.
1602 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1603 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1604 /// * *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.
1605 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1606 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1607 pub fn param<T>(mut self, name: T, value: T) -> OperationDeleteCall<'a, C>
1608 where
1609 T: AsRef<str>,
1610 {
1611 self._additional_params
1612 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1613 self
1614 }
1615
1616 /// Identifies the authorization scope for the method you are building.
1617 ///
1618 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1619 /// [`Scope::CloudPlatform`].
1620 ///
1621 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1622 /// tokens for more than one scope.
1623 ///
1624 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1625 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1626 /// sufficient, a read-write scope will do as well.
1627 pub fn add_scope<St>(mut self, scope: St) -> OperationDeleteCall<'a, C>
1628 where
1629 St: AsRef<str>,
1630 {
1631 self._scopes.insert(String::from(scope.as_ref()));
1632 self
1633 }
1634 /// Identifies the authorization scope(s) for the method you are building.
1635 ///
1636 /// See [`Self::add_scope()`] for details.
1637 pub fn add_scopes<I, St>(mut self, scopes: I) -> OperationDeleteCall<'a, C>
1638 where
1639 I: IntoIterator<Item = St>,
1640 St: AsRef<str>,
1641 {
1642 self._scopes
1643 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1644 self
1645 }
1646
1647 /// Removes all scopes, and no default scope will be used either.
1648 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1649 /// for details).
1650 pub fn clear_scopes(mut self) -> OperationDeleteCall<'a, C> {
1651 self._scopes.clear();
1652 self
1653 }
1654}
1655
1656/// Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
1657///
1658/// A builder for the *locations.operations.get* method supported by a *project* resource.
1659/// It is not used directly, but through a [`ProjectMethods`] instance.
1660///
1661/// # Example
1662///
1663/// Instantiate a resource method builder
1664///
1665/// ```test_harness,no_run
1666/// # extern crate hyper;
1667/// # extern crate hyper_rustls;
1668/// # extern crate google_texttospeech1 as texttospeech1;
1669/// # async fn dox() {
1670/// # use texttospeech1::{Texttospeech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1671///
1672/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1673/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1674/// # .with_native_roots()
1675/// # .unwrap()
1676/// # .https_only()
1677/// # .enable_http2()
1678/// # .build();
1679///
1680/// # let executor = hyper_util::rt::TokioExecutor::new();
1681/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1682/// # secret,
1683/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1684/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1685/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1686/// # ),
1687/// # ).build().await.unwrap();
1688///
1689/// # let client = hyper_util::client::legacy::Client::builder(
1690/// # hyper_util::rt::TokioExecutor::new()
1691/// # )
1692/// # .build(
1693/// # hyper_rustls::HttpsConnectorBuilder::new()
1694/// # .with_native_roots()
1695/// # .unwrap()
1696/// # .https_or_http()
1697/// # .enable_http2()
1698/// # .build()
1699/// # );
1700/// # let mut hub = Texttospeech::new(client, auth);
1701/// // You can configure optional parameters by calling the respective setters at will, and
1702/// // execute the final call using `doit()`.
1703/// // Values shown here are possibly random and not representative !
1704/// let result = hub.projects().locations_operations_get("name")
1705/// .doit().await;
1706/// # }
1707/// ```
1708pub struct ProjectLocationOperationGetCall<'a, C>
1709where
1710 C: 'a,
1711{
1712 hub: &'a Texttospeech<C>,
1713 _name: String,
1714 _delegate: Option<&'a mut dyn common::Delegate>,
1715 _additional_params: HashMap<String, String>,
1716 _scopes: BTreeSet<String>,
1717}
1718
1719impl<'a, C> common::CallBuilder for ProjectLocationOperationGetCall<'a, C> {}
1720
1721impl<'a, C> ProjectLocationOperationGetCall<'a, C>
1722where
1723 C: common::Connector,
1724{
1725 /// Perform the operation you have build so far.
1726 pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
1727 use std::borrow::Cow;
1728 use std::io::{Read, Seek};
1729
1730 use common::{url::Params, ToParts};
1731 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1732
1733 let mut dd = common::DefaultDelegate;
1734 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1735 dlg.begin(common::MethodInfo {
1736 id: "texttospeech.projects.locations.operations.get",
1737 http_method: hyper::Method::GET,
1738 });
1739
1740 for &field in ["alt", "name"].iter() {
1741 if self._additional_params.contains_key(field) {
1742 dlg.finished(false);
1743 return Err(common::Error::FieldClash(field));
1744 }
1745 }
1746
1747 let mut params = Params::with_capacity(3 + self._additional_params.len());
1748 params.push("name", self._name);
1749
1750 params.extend(self._additional_params.iter());
1751
1752 params.push("alt", "json");
1753 let mut url = self.hub._base_url.clone() + "v1/{+name}";
1754 if self._scopes.is_empty() {
1755 self._scopes
1756 .insert(Scope::CloudPlatform.as_ref().to_string());
1757 }
1758
1759 #[allow(clippy::single_element_loop)]
1760 for &(find_this, param_name) in [("{+name}", "name")].iter() {
1761 url = params.uri_replacement(url, param_name, find_this, true);
1762 }
1763 {
1764 let to_remove = ["name"];
1765 params.remove_params(&to_remove);
1766 }
1767
1768 let url = params.parse_with_url(&url);
1769
1770 loop {
1771 let token = match self
1772 .hub
1773 .auth
1774 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1775 .await
1776 {
1777 Ok(token) => token,
1778 Err(e) => match dlg.token(e) {
1779 Ok(token) => token,
1780 Err(e) => {
1781 dlg.finished(false);
1782 return Err(common::Error::MissingToken(e));
1783 }
1784 },
1785 };
1786 let mut req_result = {
1787 let client = &self.hub.client;
1788 dlg.pre_request();
1789 let mut req_builder = hyper::Request::builder()
1790 .method(hyper::Method::GET)
1791 .uri(url.as_str())
1792 .header(USER_AGENT, self.hub._user_agent.clone());
1793
1794 if let Some(token) = token.as_ref() {
1795 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1796 }
1797
1798 let request = req_builder
1799 .header(CONTENT_LENGTH, 0_u64)
1800 .body(common::to_body::<String>(None));
1801
1802 client.request(request.unwrap()).await
1803 };
1804
1805 match req_result {
1806 Err(err) => {
1807 if let common::Retry::After(d) = dlg.http_error(&err) {
1808 sleep(d).await;
1809 continue;
1810 }
1811 dlg.finished(false);
1812 return Err(common::Error::HttpError(err));
1813 }
1814 Ok(res) => {
1815 let (mut parts, body) = res.into_parts();
1816 let mut body = common::Body::new(body);
1817 if !parts.status.is_success() {
1818 let bytes = common::to_bytes(body).await.unwrap_or_default();
1819 let error = serde_json::from_str(&common::to_string(&bytes));
1820 let response = common::to_response(parts, bytes.into());
1821
1822 if let common::Retry::After(d) =
1823 dlg.http_failure(&response, error.as_ref().ok())
1824 {
1825 sleep(d).await;
1826 continue;
1827 }
1828
1829 dlg.finished(false);
1830
1831 return Err(match error {
1832 Ok(value) => common::Error::BadRequest(value),
1833 _ => common::Error::Failure(response),
1834 });
1835 }
1836 let response = {
1837 let bytes = common::to_bytes(body).await.unwrap_or_default();
1838 let encoded = common::to_string(&bytes);
1839 match serde_json::from_str(&encoded) {
1840 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1841 Err(error) => {
1842 dlg.response_json_decode_error(&encoded, &error);
1843 return Err(common::Error::JsonDecodeError(
1844 encoded.to_string(),
1845 error,
1846 ));
1847 }
1848 }
1849 };
1850
1851 dlg.finished(true);
1852 return Ok(response);
1853 }
1854 }
1855 }
1856 }
1857
1858 /// The name of the operation resource.
1859 ///
1860 /// Sets the *name* path property to the given value.
1861 ///
1862 /// Even though the property as already been set when instantiating this call,
1863 /// we provide this method for API completeness.
1864 pub fn name(mut self, new_value: &str) -> ProjectLocationOperationGetCall<'a, C> {
1865 self._name = new_value.to_string();
1866 self
1867 }
1868 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1869 /// while executing the actual API request.
1870 ///
1871 /// ````text
1872 /// It should be used to handle progress information, and to implement a certain level of resilience.
1873 /// ````
1874 ///
1875 /// Sets the *delegate* property to the given value.
1876 pub fn delegate(
1877 mut self,
1878 new_value: &'a mut dyn common::Delegate,
1879 ) -> ProjectLocationOperationGetCall<'a, C> {
1880 self._delegate = Some(new_value);
1881 self
1882 }
1883
1884 /// Set any additional parameter of the query string used in the request.
1885 /// It should be used to set parameters which are not yet available through their own
1886 /// setters.
1887 ///
1888 /// Please note that this method must not be used to set any of the known parameters
1889 /// which have their own setter method. If done anyway, the request will fail.
1890 ///
1891 /// # Additional Parameters
1892 ///
1893 /// * *$.xgafv* (query-string) - V1 error format.
1894 /// * *access_token* (query-string) - OAuth access token.
1895 /// * *alt* (query-string) - Data format for response.
1896 /// * *callback* (query-string) - JSONP
1897 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1898 /// * *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.
1899 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1900 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1901 /// * *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.
1902 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1903 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1904 pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationOperationGetCall<'a, C>
1905 where
1906 T: AsRef<str>,
1907 {
1908 self._additional_params
1909 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1910 self
1911 }
1912
1913 /// Identifies the authorization scope for the method you are building.
1914 ///
1915 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1916 /// [`Scope::CloudPlatform`].
1917 ///
1918 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1919 /// tokens for more than one scope.
1920 ///
1921 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1922 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1923 /// sufficient, a read-write scope will do as well.
1924 pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationOperationGetCall<'a, C>
1925 where
1926 St: AsRef<str>,
1927 {
1928 self._scopes.insert(String::from(scope.as_ref()));
1929 self
1930 }
1931 /// Identifies the authorization scope(s) for the method you are building.
1932 ///
1933 /// See [`Self::add_scope()`] for details.
1934 pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationOperationGetCall<'a, C>
1935 where
1936 I: IntoIterator<Item = St>,
1937 St: AsRef<str>,
1938 {
1939 self._scopes
1940 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1941 self
1942 }
1943
1944 /// Removes all scopes, and no default scope will be used either.
1945 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1946 /// for details).
1947 pub fn clear_scopes(mut self) -> ProjectLocationOperationGetCall<'a, C> {
1948 self._scopes.clear();
1949 self
1950 }
1951}
1952
1953/// Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`.
1954///
1955/// A builder for the *locations.operations.list* method supported by a *project* resource.
1956/// It is not used directly, but through a [`ProjectMethods`] instance.
1957///
1958/// # Example
1959///
1960/// Instantiate a resource method builder
1961///
1962/// ```test_harness,no_run
1963/// # extern crate hyper;
1964/// # extern crate hyper_rustls;
1965/// # extern crate google_texttospeech1 as texttospeech1;
1966/// # async fn dox() {
1967/// # use texttospeech1::{Texttospeech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1968///
1969/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1970/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1971/// # .with_native_roots()
1972/// # .unwrap()
1973/// # .https_only()
1974/// # .enable_http2()
1975/// # .build();
1976///
1977/// # let executor = hyper_util::rt::TokioExecutor::new();
1978/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1979/// # secret,
1980/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1981/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1982/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1983/// # ),
1984/// # ).build().await.unwrap();
1985///
1986/// # let client = hyper_util::client::legacy::Client::builder(
1987/// # hyper_util::rt::TokioExecutor::new()
1988/// # )
1989/// # .build(
1990/// # hyper_rustls::HttpsConnectorBuilder::new()
1991/// # .with_native_roots()
1992/// # .unwrap()
1993/// # .https_or_http()
1994/// # .enable_http2()
1995/// # .build()
1996/// # );
1997/// # let mut hub = Texttospeech::new(client, auth);
1998/// // You can configure optional parameters by calling the respective setters at will, and
1999/// // execute the final call using `doit()`.
2000/// // Values shown here are possibly random and not representative !
2001/// let result = hub.projects().locations_operations_list("name")
2002/// .return_partial_success(false)
2003/// .page_token("amet.")
2004/// .page_size(-59)
2005/// .filter("amet.")
2006/// .doit().await;
2007/// # }
2008/// ```
2009pub struct ProjectLocationOperationListCall<'a, C>
2010where
2011 C: 'a,
2012{
2013 hub: &'a Texttospeech<C>,
2014 _name: String,
2015 _return_partial_success: Option<bool>,
2016 _page_token: Option<String>,
2017 _page_size: Option<i32>,
2018 _filter: Option<String>,
2019 _delegate: Option<&'a mut dyn common::Delegate>,
2020 _additional_params: HashMap<String, String>,
2021 _scopes: BTreeSet<String>,
2022}
2023
2024impl<'a, C> common::CallBuilder for ProjectLocationOperationListCall<'a, C> {}
2025
2026impl<'a, C> ProjectLocationOperationListCall<'a, C>
2027where
2028 C: common::Connector,
2029{
2030 /// Perform the operation you have build so far.
2031 pub async fn doit(mut self) -> common::Result<(common::Response, ListOperationsResponse)> {
2032 use std::borrow::Cow;
2033 use std::io::{Read, Seek};
2034
2035 use common::{url::Params, ToParts};
2036 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2037
2038 let mut dd = common::DefaultDelegate;
2039 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2040 dlg.begin(common::MethodInfo {
2041 id: "texttospeech.projects.locations.operations.list",
2042 http_method: hyper::Method::GET,
2043 });
2044
2045 for &field in [
2046 "alt",
2047 "name",
2048 "returnPartialSuccess",
2049 "pageToken",
2050 "pageSize",
2051 "filter",
2052 ]
2053 .iter()
2054 {
2055 if self._additional_params.contains_key(field) {
2056 dlg.finished(false);
2057 return Err(common::Error::FieldClash(field));
2058 }
2059 }
2060
2061 let mut params = Params::with_capacity(7 + self._additional_params.len());
2062 params.push("name", self._name);
2063 if let Some(value) = self._return_partial_success.as_ref() {
2064 params.push("returnPartialSuccess", value.to_string());
2065 }
2066 if let Some(value) = self._page_token.as_ref() {
2067 params.push("pageToken", value);
2068 }
2069 if let Some(value) = self._page_size.as_ref() {
2070 params.push("pageSize", value.to_string());
2071 }
2072 if let Some(value) = self._filter.as_ref() {
2073 params.push("filter", value);
2074 }
2075
2076 params.extend(self._additional_params.iter());
2077
2078 params.push("alt", "json");
2079 let mut url = self.hub._base_url.clone() + "v1/{+name}/operations";
2080 if self._scopes.is_empty() {
2081 self._scopes
2082 .insert(Scope::CloudPlatform.as_ref().to_string());
2083 }
2084
2085 #[allow(clippy::single_element_loop)]
2086 for &(find_this, param_name) in [("{+name}", "name")].iter() {
2087 url = params.uri_replacement(url, param_name, find_this, true);
2088 }
2089 {
2090 let to_remove = ["name"];
2091 params.remove_params(&to_remove);
2092 }
2093
2094 let url = params.parse_with_url(&url);
2095
2096 loop {
2097 let token = match self
2098 .hub
2099 .auth
2100 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2101 .await
2102 {
2103 Ok(token) => token,
2104 Err(e) => match dlg.token(e) {
2105 Ok(token) => token,
2106 Err(e) => {
2107 dlg.finished(false);
2108 return Err(common::Error::MissingToken(e));
2109 }
2110 },
2111 };
2112 let mut req_result = {
2113 let client = &self.hub.client;
2114 dlg.pre_request();
2115 let mut req_builder = hyper::Request::builder()
2116 .method(hyper::Method::GET)
2117 .uri(url.as_str())
2118 .header(USER_AGENT, self.hub._user_agent.clone());
2119
2120 if let Some(token) = token.as_ref() {
2121 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2122 }
2123
2124 let request = req_builder
2125 .header(CONTENT_LENGTH, 0_u64)
2126 .body(common::to_body::<String>(None));
2127
2128 client.request(request.unwrap()).await
2129 };
2130
2131 match req_result {
2132 Err(err) => {
2133 if let common::Retry::After(d) = dlg.http_error(&err) {
2134 sleep(d).await;
2135 continue;
2136 }
2137 dlg.finished(false);
2138 return Err(common::Error::HttpError(err));
2139 }
2140 Ok(res) => {
2141 let (mut parts, body) = res.into_parts();
2142 let mut body = common::Body::new(body);
2143 if !parts.status.is_success() {
2144 let bytes = common::to_bytes(body).await.unwrap_or_default();
2145 let error = serde_json::from_str(&common::to_string(&bytes));
2146 let response = common::to_response(parts, bytes.into());
2147
2148 if let common::Retry::After(d) =
2149 dlg.http_failure(&response, error.as_ref().ok())
2150 {
2151 sleep(d).await;
2152 continue;
2153 }
2154
2155 dlg.finished(false);
2156
2157 return Err(match error {
2158 Ok(value) => common::Error::BadRequest(value),
2159 _ => common::Error::Failure(response),
2160 });
2161 }
2162 let response = {
2163 let bytes = common::to_bytes(body).await.unwrap_or_default();
2164 let encoded = common::to_string(&bytes);
2165 match serde_json::from_str(&encoded) {
2166 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2167 Err(error) => {
2168 dlg.response_json_decode_error(&encoded, &error);
2169 return Err(common::Error::JsonDecodeError(
2170 encoded.to_string(),
2171 error,
2172 ));
2173 }
2174 }
2175 };
2176
2177 dlg.finished(true);
2178 return Ok(response);
2179 }
2180 }
2181 }
2182 }
2183
2184 /// The name of the operation's parent resource.
2185 ///
2186 /// Sets the *name* path property to the given value.
2187 ///
2188 /// Even though the property as already been set when instantiating this call,
2189 /// we provide this method for API completeness.
2190 pub fn name(mut self, new_value: &str) -> ProjectLocationOperationListCall<'a, C> {
2191 self._name = new_value.to_string();
2192 self
2193 }
2194 /// When set to `true`, operations that are reachable are returned as normal, and those that are unreachable are returned in the ListOperationsResponse.unreachable field. This can only be `true` when reading across collections. For example, when `parent` is set to `"projects/example/locations/-"`. This field is not supported by default and will result in an `UNIMPLEMENTED` error if set unless explicitly documented otherwise in service or product specific documentation.
2195 ///
2196 /// Sets the *return partial success* query property to the given value.
2197 pub fn return_partial_success(
2198 mut self,
2199 new_value: bool,
2200 ) -> ProjectLocationOperationListCall<'a, C> {
2201 self._return_partial_success = Some(new_value);
2202 self
2203 }
2204 /// The standard list page token.
2205 ///
2206 /// Sets the *page token* query property to the given value.
2207 pub fn page_token(mut self, new_value: &str) -> ProjectLocationOperationListCall<'a, C> {
2208 self._page_token = Some(new_value.to_string());
2209 self
2210 }
2211 /// The standard list page size.
2212 ///
2213 /// Sets the *page size* query property to the given value.
2214 pub fn page_size(mut self, new_value: i32) -> ProjectLocationOperationListCall<'a, C> {
2215 self._page_size = Some(new_value);
2216 self
2217 }
2218 /// The standard list filter.
2219 ///
2220 /// Sets the *filter* query property to the given value.
2221 pub fn filter(mut self, new_value: &str) -> ProjectLocationOperationListCall<'a, C> {
2222 self._filter = Some(new_value.to_string());
2223 self
2224 }
2225 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2226 /// while executing the actual API request.
2227 ///
2228 /// ````text
2229 /// It should be used to handle progress information, and to implement a certain level of resilience.
2230 /// ````
2231 ///
2232 /// Sets the *delegate* property to the given value.
2233 pub fn delegate(
2234 mut self,
2235 new_value: &'a mut dyn common::Delegate,
2236 ) -> ProjectLocationOperationListCall<'a, C> {
2237 self._delegate = Some(new_value);
2238 self
2239 }
2240
2241 /// Set any additional parameter of the query string used in the request.
2242 /// It should be used to set parameters which are not yet available through their own
2243 /// setters.
2244 ///
2245 /// Please note that this method must not be used to set any of the known parameters
2246 /// which have their own setter method. If done anyway, the request will fail.
2247 ///
2248 /// # Additional Parameters
2249 ///
2250 /// * *$.xgafv* (query-string) - V1 error format.
2251 /// * *access_token* (query-string) - OAuth access token.
2252 /// * *alt* (query-string) - Data format for response.
2253 /// * *callback* (query-string) - JSONP
2254 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2255 /// * *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.
2256 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2257 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2258 /// * *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.
2259 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2260 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2261 pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationOperationListCall<'a, C>
2262 where
2263 T: AsRef<str>,
2264 {
2265 self._additional_params
2266 .insert(name.as_ref().to_string(), value.as_ref().to_string());
2267 self
2268 }
2269
2270 /// Identifies the authorization scope for the method you are building.
2271 ///
2272 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2273 /// [`Scope::CloudPlatform`].
2274 ///
2275 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2276 /// tokens for more than one scope.
2277 ///
2278 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2279 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2280 /// sufficient, a read-write scope will do as well.
2281 pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationOperationListCall<'a, C>
2282 where
2283 St: AsRef<str>,
2284 {
2285 self._scopes.insert(String::from(scope.as_ref()));
2286 self
2287 }
2288 /// Identifies the authorization scope(s) for the method you are building.
2289 ///
2290 /// See [`Self::add_scope()`] for details.
2291 pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationOperationListCall<'a, C>
2292 where
2293 I: IntoIterator<Item = St>,
2294 St: AsRef<str>,
2295 {
2296 self._scopes
2297 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2298 self
2299 }
2300
2301 /// Removes all scopes, and no default scope will be used either.
2302 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2303 /// for details).
2304 pub fn clear_scopes(mut self) -> ProjectLocationOperationListCall<'a, C> {
2305 self._scopes.clear();
2306 self
2307 }
2308}
2309
2310/// Synthesizes long form text asynchronously.
2311///
2312/// A builder for the *locations.synthesizeLongAudio* method supported by a *project* resource.
2313/// It is not used directly, but through a [`ProjectMethods`] instance.
2314///
2315/// # Example
2316///
2317/// Instantiate a resource method builder
2318///
2319/// ```test_harness,no_run
2320/// # extern crate hyper;
2321/// # extern crate hyper_rustls;
2322/// # extern crate google_texttospeech1 as texttospeech1;
2323/// use texttospeech1::api::SynthesizeLongAudioRequest;
2324/// # async fn dox() {
2325/// # use texttospeech1::{Texttospeech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2326///
2327/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2328/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2329/// # .with_native_roots()
2330/// # .unwrap()
2331/// # .https_only()
2332/// # .enable_http2()
2333/// # .build();
2334///
2335/// # let executor = hyper_util::rt::TokioExecutor::new();
2336/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2337/// # secret,
2338/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2339/// # yup_oauth2::client::CustomHyperClientBuilder::from(
2340/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
2341/// # ),
2342/// # ).build().await.unwrap();
2343///
2344/// # let client = hyper_util::client::legacy::Client::builder(
2345/// # hyper_util::rt::TokioExecutor::new()
2346/// # )
2347/// # .build(
2348/// # hyper_rustls::HttpsConnectorBuilder::new()
2349/// # .with_native_roots()
2350/// # .unwrap()
2351/// # .https_or_http()
2352/// # .enable_http2()
2353/// # .build()
2354/// # );
2355/// # let mut hub = Texttospeech::new(client, auth);
2356/// // As the method needs a request, you would usually fill it with the desired information
2357/// // into the respective structure. Some of the parts shown here might not be applicable !
2358/// // Values shown here are possibly random and not representative !
2359/// let mut req = SynthesizeLongAudioRequest::default();
2360///
2361/// // You can configure optional parameters by calling the respective setters at will, and
2362/// // execute the final call using `doit()`.
2363/// // Values shown here are possibly random and not representative !
2364/// let result = hub.projects().locations_synthesize_long_audio(req, "parent")
2365/// .doit().await;
2366/// # }
2367/// ```
2368pub struct ProjectLocationSynthesizeLongAudioCall<'a, C>
2369where
2370 C: 'a,
2371{
2372 hub: &'a Texttospeech<C>,
2373 _request: SynthesizeLongAudioRequest,
2374 _parent: String,
2375 _delegate: Option<&'a mut dyn common::Delegate>,
2376 _additional_params: HashMap<String, String>,
2377 _scopes: BTreeSet<String>,
2378}
2379
2380impl<'a, C> common::CallBuilder for ProjectLocationSynthesizeLongAudioCall<'a, C> {}
2381
2382impl<'a, C> ProjectLocationSynthesizeLongAudioCall<'a, C>
2383where
2384 C: common::Connector,
2385{
2386 /// Perform the operation you have build so far.
2387 pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
2388 use std::borrow::Cow;
2389 use std::io::{Read, Seek};
2390
2391 use common::{url::Params, ToParts};
2392 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2393
2394 let mut dd = common::DefaultDelegate;
2395 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2396 dlg.begin(common::MethodInfo {
2397 id: "texttospeech.projects.locations.synthesizeLongAudio",
2398 http_method: hyper::Method::POST,
2399 });
2400
2401 for &field in ["alt", "parent"].iter() {
2402 if self._additional_params.contains_key(field) {
2403 dlg.finished(false);
2404 return Err(common::Error::FieldClash(field));
2405 }
2406 }
2407
2408 let mut params = Params::with_capacity(4 + self._additional_params.len());
2409 params.push("parent", self._parent);
2410
2411 params.extend(self._additional_params.iter());
2412
2413 params.push("alt", "json");
2414 let mut url = self.hub._base_url.clone() + "v1/{+parent}:synthesizeLongAudio";
2415 if self._scopes.is_empty() {
2416 self._scopes
2417 .insert(Scope::CloudPlatform.as_ref().to_string());
2418 }
2419
2420 #[allow(clippy::single_element_loop)]
2421 for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
2422 url = params.uri_replacement(url, param_name, find_this, true);
2423 }
2424 {
2425 let to_remove = ["parent"];
2426 params.remove_params(&to_remove);
2427 }
2428
2429 let url = params.parse_with_url(&url);
2430
2431 let mut json_mime_type = mime::APPLICATION_JSON;
2432 let mut request_value_reader = {
2433 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2434 common::remove_json_null_values(&mut value);
2435 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2436 serde_json::to_writer(&mut dst, &value).unwrap();
2437 dst
2438 };
2439 let request_size = request_value_reader
2440 .seek(std::io::SeekFrom::End(0))
2441 .unwrap();
2442 request_value_reader
2443 .seek(std::io::SeekFrom::Start(0))
2444 .unwrap();
2445
2446 loop {
2447 let token = match self
2448 .hub
2449 .auth
2450 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2451 .await
2452 {
2453 Ok(token) => token,
2454 Err(e) => match dlg.token(e) {
2455 Ok(token) => token,
2456 Err(e) => {
2457 dlg.finished(false);
2458 return Err(common::Error::MissingToken(e));
2459 }
2460 },
2461 };
2462 request_value_reader
2463 .seek(std::io::SeekFrom::Start(0))
2464 .unwrap();
2465 let mut req_result = {
2466 let client = &self.hub.client;
2467 dlg.pre_request();
2468 let mut req_builder = hyper::Request::builder()
2469 .method(hyper::Method::POST)
2470 .uri(url.as_str())
2471 .header(USER_AGENT, self.hub._user_agent.clone());
2472
2473 if let Some(token) = token.as_ref() {
2474 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2475 }
2476
2477 let request = req_builder
2478 .header(CONTENT_TYPE, json_mime_type.to_string())
2479 .header(CONTENT_LENGTH, request_size as u64)
2480 .body(common::to_body(
2481 request_value_reader.get_ref().clone().into(),
2482 ));
2483
2484 client.request(request.unwrap()).await
2485 };
2486
2487 match req_result {
2488 Err(err) => {
2489 if let common::Retry::After(d) = dlg.http_error(&err) {
2490 sleep(d).await;
2491 continue;
2492 }
2493 dlg.finished(false);
2494 return Err(common::Error::HttpError(err));
2495 }
2496 Ok(res) => {
2497 let (mut parts, body) = res.into_parts();
2498 let mut body = common::Body::new(body);
2499 if !parts.status.is_success() {
2500 let bytes = common::to_bytes(body).await.unwrap_or_default();
2501 let error = serde_json::from_str(&common::to_string(&bytes));
2502 let response = common::to_response(parts, bytes.into());
2503
2504 if let common::Retry::After(d) =
2505 dlg.http_failure(&response, error.as_ref().ok())
2506 {
2507 sleep(d).await;
2508 continue;
2509 }
2510
2511 dlg.finished(false);
2512
2513 return Err(match error {
2514 Ok(value) => common::Error::BadRequest(value),
2515 _ => common::Error::Failure(response),
2516 });
2517 }
2518 let response = {
2519 let bytes = common::to_bytes(body).await.unwrap_or_default();
2520 let encoded = common::to_string(&bytes);
2521 match serde_json::from_str(&encoded) {
2522 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2523 Err(error) => {
2524 dlg.response_json_decode_error(&encoded, &error);
2525 return Err(common::Error::JsonDecodeError(
2526 encoded.to_string(),
2527 error,
2528 ));
2529 }
2530 }
2531 };
2532
2533 dlg.finished(true);
2534 return Ok(response);
2535 }
2536 }
2537 }
2538 }
2539
2540 ///
2541 /// Sets the *request* property to the given value.
2542 ///
2543 /// Even though the property as already been set when instantiating this call,
2544 /// we provide this method for API completeness.
2545 pub fn request(
2546 mut self,
2547 new_value: SynthesizeLongAudioRequest,
2548 ) -> ProjectLocationSynthesizeLongAudioCall<'a, C> {
2549 self._request = new_value;
2550 self
2551 }
2552 /// The resource states of the request in the form of `projects/*/locations/*`.
2553 ///
2554 /// Sets the *parent* path property to the given value.
2555 ///
2556 /// Even though the property as already been set when instantiating this call,
2557 /// we provide this method for API completeness.
2558 pub fn parent(mut self, new_value: &str) -> ProjectLocationSynthesizeLongAudioCall<'a, C> {
2559 self._parent = new_value.to_string();
2560 self
2561 }
2562 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2563 /// while executing the actual API request.
2564 ///
2565 /// ````text
2566 /// It should be used to handle progress information, and to implement a certain level of resilience.
2567 /// ````
2568 ///
2569 /// Sets the *delegate* property to the given value.
2570 pub fn delegate(
2571 mut self,
2572 new_value: &'a mut dyn common::Delegate,
2573 ) -> ProjectLocationSynthesizeLongAudioCall<'a, C> {
2574 self._delegate = Some(new_value);
2575 self
2576 }
2577
2578 /// Set any additional parameter of the query string used in the request.
2579 /// It should be used to set parameters which are not yet available through their own
2580 /// setters.
2581 ///
2582 /// Please note that this method must not be used to set any of the known parameters
2583 /// which have their own setter method. If done anyway, the request will fail.
2584 ///
2585 /// # Additional Parameters
2586 ///
2587 /// * *$.xgafv* (query-string) - V1 error format.
2588 /// * *access_token* (query-string) - OAuth access token.
2589 /// * *alt* (query-string) - Data format for response.
2590 /// * *callback* (query-string) - JSONP
2591 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2592 /// * *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.
2593 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2594 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2595 /// * *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.
2596 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2597 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2598 pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationSynthesizeLongAudioCall<'a, C>
2599 where
2600 T: AsRef<str>,
2601 {
2602 self._additional_params
2603 .insert(name.as_ref().to_string(), value.as_ref().to_string());
2604 self
2605 }
2606
2607 /// Identifies the authorization scope for the method you are building.
2608 ///
2609 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2610 /// [`Scope::CloudPlatform`].
2611 ///
2612 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2613 /// tokens for more than one scope.
2614 ///
2615 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2616 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2617 /// sufficient, a read-write scope will do as well.
2618 pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationSynthesizeLongAudioCall<'a, C>
2619 where
2620 St: AsRef<str>,
2621 {
2622 self._scopes.insert(String::from(scope.as_ref()));
2623 self
2624 }
2625 /// Identifies the authorization scope(s) for the method you are building.
2626 ///
2627 /// See [`Self::add_scope()`] for details.
2628 pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationSynthesizeLongAudioCall<'a, C>
2629 where
2630 I: IntoIterator<Item = St>,
2631 St: AsRef<str>,
2632 {
2633 self._scopes
2634 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2635 self
2636 }
2637
2638 /// Removes all scopes, and no default scope will be used either.
2639 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2640 /// for details).
2641 pub fn clear_scopes(mut self) -> ProjectLocationSynthesizeLongAudioCall<'a, C> {
2642 self._scopes.clear();
2643 self
2644 }
2645}
2646
2647/// Synthesizes speech synchronously: receive results after all text input has been processed.
2648///
2649/// A builder for the *synthesize* method supported by a *text* resource.
2650/// It is not used directly, but through a [`TextMethods`] instance.
2651///
2652/// # Example
2653///
2654/// Instantiate a resource method builder
2655///
2656/// ```test_harness,no_run
2657/// # extern crate hyper;
2658/// # extern crate hyper_rustls;
2659/// # extern crate google_texttospeech1 as texttospeech1;
2660/// use texttospeech1::api::SynthesizeSpeechRequest;
2661/// # async fn dox() {
2662/// # use texttospeech1::{Texttospeech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2663///
2664/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2665/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2666/// # .with_native_roots()
2667/// # .unwrap()
2668/// # .https_only()
2669/// # .enable_http2()
2670/// # .build();
2671///
2672/// # let executor = hyper_util::rt::TokioExecutor::new();
2673/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2674/// # secret,
2675/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2676/// # yup_oauth2::client::CustomHyperClientBuilder::from(
2677/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
2678/// # ),
2679/// # ).build().await.unwrap();
2680///
2681/// # let client = hyper_util::client::legacy::Client::builder(
2682/// # hyper_util::rt::TokioExecutor::new()
2683/// # )
2684/// # .build(
2685/// # hyper_rustls::HttpsConnectorBuilder::new()
2686/// # .with_native_roots()
2687/// # .unwrap()
2688/// # .https_or_http()
2689/// # .enable_http2()
2690/// # .build()
2691/// # );
2692/// # let mut hub = Texttospeech::new(client, auth);
2693/// // As the method needs a request, you would usually fill it with the desired information
2694/// // into the respective structure. Some of the parts shown here might not be applicable !
2695/// // Values shown here are possibly random and not representative !
2696/// let mut req = SynthesizeSpeechRequest::default();
2697///
2698/// // You can configure optional parameters by calling the respective setters at will, and
2699/// // execute the final call using `doit()`.
2700/// // Values shown here are possibly random and not representative !
2701/// let result = hub.text().synthesize(req)
2702/// .doit().await;
2703/// # }
2704/// ```
2705pub struct TextSynthesizeCall<'a, C>
2706where
2707 C: 'a,
2708{
2709 hub: &'a Texttospeech<C>,
2710 _request: SynthesizeSpeechRequest,
2711 _delegate: Option<&'a mut dyn common::Delegate>,
2712 _additional_params: HashMap<String, String>,
2713 _scopes: BTreeSet<String>,
2714}
2715
2716impl<'a, C> common::CallBuilder for TextSynthesizeCall<'a, C> {}
2717
2718impl<'a, C> TextSynthesizeCall<'a, C>
2719where
2720 C: common::Connector,
2721{
2722 /// Perform the operation you have build so far.
2723 pub async fn doit(mut self) -> common::Result<(common::Response, SynthesizeSpeechResponse)> {
2724 use std::borrow::Cow;
2725 use std::io::{Read, Seek};
2726
2727 use common::{url::Params, ToParts};
2728 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2729
2730 let mut dd = common::DefaultDelegate;
2731 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2732 dlg.begin(common::MethodInfo {
2733 id: "texttospeech.text.synthesize",
2734 http_method: hyper::Method::POST,
2735 });
2736
2737 for &field in ["alt"].iter() {
2738 if self._additional_params.contains_key(field) {
2739 dlg.finished(false);
2740 return Err(common::Error::FieldClash(field));
2741 }
2742 }
2743
2744 let mut params = Params::with_capacity(3 + self._additional_params.len());
2745
2746 params.extend(self._additional_params.iter());
2747
2748 params.push("alt", "json");
2749 let mut url = self.hub._base_url.clone() + "v1/text:synthesize";
2750 if self._scopes.is_empty() {
2751 self._scopes
2752 .insert(Scope::CloudPlatform.as_ref().to_string());
2753 }
2754
2755 let url = params.parse_with_url(&url);
2756
2757 let mut json_mime_type = mime::APPLICATION_JSON;
2758 let mut request_value_reader = {
2759 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2760 common::remove_json_null_values(&mut value);
2761 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2762 serde_json::to_writer(&mut dst, &value).unwrap();
2763 dst
2764 };
2765 let request_size = request_value_reader
2766 .seek(std::io::SeekFrom::End(0))
2767 .unwrap();
2768 request_value_reader
2769 .seek(std::io::SeekFrom::Start(0))
2770 .unwrap();
2771
2772 loop {
2773 let token = match self
2774 .hub
2775 .auth
2776 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2777 .await
2778 {
2779 Ok(token) => token,
2780 Err(e) => match dlg.token(e) {
2781 Ok(token) => token,
2782 Err(e) => {
2783 dlg.finished(false);
2784 return Err(common::Error::MissingToken(e));
2785 }
2786 },
2787 };
2788 request_value_reader
2789 .seek(std::io::SeekFrom::Start(0))
2790 .unwrap();
2791 let mut req_result = {
2792 let client = &self.hub.client;
2793 dlg.pre_request();
2794 let mut req_builder = hyper::Request::builder()
2795 .method(hyper::Method::POST)
2796 .uri(url.as_str())
2797 .header(USER_AGENT, self.hub._user_agent.clone());
2798
2799 if let Some(token) = token.as_ref() {
2800 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2801 }
2802
2803 let request = req_builder
2804 .header(CONTENT_TYPE, json_mime_type.to_string())
2805 .header(CONTENT_LENGTH, request_size as u64)
2806 .body(common::to_body(
2807 request_value_reader.get_ref().clone().into(),
2808 ));
2809
2810 client.request(request.unwrap()).await
2811 };
2812
2813 match req_result {
2814 Err(err) => {
2815 if let common::Retry::After(d) = dlg.http_error(&err) {
2816 sleep(d).await;
2817 continue;
2818 }
2819 dlg.finished(false);
2820 return Err(common::Error::HttpError(err));
2821 }
2822 Ok(res) => {
2823 let (mut parts, body) = res.into_parts();
2824 let mut body = common::Body::new(body);
2825 if !parts.status.is_success() {
2826 let bytes = common::to_bytes(body).await.unwrap_or_default();
2827 let error = serde_json::from_str(&common::to_string(&bytes));
2828 let response = common::to_response(parts, bytes.into());
2829
2830 if let common::Retry::After(d) =
2831 dlg.http_failure(&response, error.as_ref().ok())
2832 {
2833 sleep(d).await;
2834 continue;
2835 }
2836
2837 dlg.finished(false);
2838
2839 return Err(match error {
2840 Ok(value) => common::Error::BadRequest(value),
2841 _ => common::Error::Failure(response),
2842 });
2843 }
2844 let response = {
2845 let bytes = common::to_bytes(body).await.unwrap_or_default();
2846 let encoded = common::to_string(&bytes);
2847 match serde_json::from_str(&encoded) {
2848 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2849 Err(error) => {
2850 dlg.response_json_decode_error(&encoded, &error);
2851 return Err(common::Error::JsonDecodeError(
2852 encoded.to_string(),
2853 error,
2854 ));
2855 }
2856 }
2857 };
2858
2859 dlg.finished(true);
2860 return Ok(response);
2861 }
2862 }
2863 }
2864 }
2865
2866 ///
2867 /// Sets the *request* property to the given value.
2868 ///
2869 /// Even though the property as already been set when instantiating this call,
2870 /// we provide this method for API completeness.
2871 pub fn request(mut self, new_value: SynthesizeSpeechRequest) -> TextSynthesizeCall<'a, C> {
2872 self._request = new_value;
2873 self
2874 }
2875 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2876 /// while executing the actual API request.
2877 ///
2878 /// ````text
2879 /// It should be used to handle progress information, and to implement a certain level of resilience.
2880 /// ````
2881 ///
2882 /// Sets the *delegate* property to the given value.
2883 pub fn delegate(
2884 mut self,
2885 new_value: &'a mut dyn common::Delegate,
2886 ) -> TextSynthesizeCall<'a, C> {
2887 self._delegate = Some(new_value);
2888 self
2889 }
2890
2891 /// Set any additional parameter of the query string used in the request.
2892 /// It should be used to set parameters which are not yet available through their own
2893 /// setters.
2894 ///
2895 /// Please note that this method must not be used to set any of the known parameters
2896 /// which have their own setter method. If done anyway, the request will fail.
2897 ///
2898 /// # Additional Parameters
2899 ///
2900 /// * *$.xgafv* (query-string) - V1 error format.
2901 /// * *access_token* (query-string) - OAuth access token.
2902 /// * *alt* (query-string) - Data format for response.
2903 /// * *callback* (query-string) - JSONP
2904 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2905 /// * *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.
2906 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2907 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2908 /// * *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.
2909 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2910 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2911 pub fn param<T>(mut self, name: T, value: T) -> TextSynthesizeCall<'a, C>
2912 where
2913 T: AsRef<str>,
2914 {
2915 self._additional_params
2916 .insert(name.as_ref().to_string(), value.as_ref().to_string());
2917 self
2918 }
2919
2920 /// Identifies the authorization scope for the method you are building.
2921 ///
2922 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2923 /// [`Scope::CloudPlatform`].
2924 ///
2925 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2926 /// tokens for more than one scope.
2927 ///
2928 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2929 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2930 /// sufficient, a read-write scope will do as well.
2931 pub fn add_scope<St>(mut self, scope: St) -> TextSynthesizeCall<'a, C>
2932 where
2933 St: AsRef<str>,
2934 {
2935 self._scopes.insert(String::from(scope.as_ref()));
2936 self
2937 }
2938 /// Identifies the authorization scope(s) for the method you are building.
2939 ///
2940 /// See [`Self::add_scope()`] for details.
2941 pub fn add_scopes<I, St>(mut self, scopes: I) -> TextSynthesizeCall<'a, C>
2942 where
2943 I: IntoIterator<Item = St>,
2944 St: AsRef<str>,
2945 {
2946 self._scopes
2947 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2948 self
2949 }
2950
2951 /// Removes all scopes, and no default scope will be used either.
2952 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2953 /// for details).
2954 pub fn clear_scopes(mut self) -> TextSynthesizeCall<'a, C> {
2955 self._scopes.clear();
2956 self
2957 }
2958}
2959
2960/// Returns a list of Voice supported for synthesis.
2961///
2962/// A builder for the *list* method supported by a *voice* resource.
2963/// It is not used directly, but through a [`VoiceMethods`] instance.
2964///
2965/// # Example
2966///
2967/// Instantiate a resource method builder
2968///
2969/// ```test_harness,no_run
2970/// # extern crate hyper;
2971/// # extern crate hyper_rustls;
2972/// # extern crate google_texttospeech1 as texttospeech1;
2973/// # async fn dox() {
2974/// # use texttospeech1::{Texttospeech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2975///
2976/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2977/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2978/// # .with_native_roots()
2979/// # .unwrap()
2980/// # .https_only()
2981/// # .enable_http2()
2982/// # .build();
2983///
2984/// # let executor = hyper_util::rt::TokioExecutor::new();
2985/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2986/// # secret,
2987/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2988/// # yup_oauth2::client::CustomHyperClientBuilder::from(
2989/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
2990/// # ),
2991/// # ).build().await.unwrap();
2992///
2993/// # let client = hyper_util::client::legacy::Client::builder(
2994/// # hyper_util::rt::TokioExecutor::new()
2995/// # )
2996/// # .build(
2997/// # hyper_rustls::HttpsConnectorBuilder::new()
2998/// # .with_native_roots()
2999/// # .unwrap()
3000/// # .https_or_http()
3001/// # .enable_http2()
3002/// # .build()
3003/// # );
3004/// # let mut hub = Texttospeech::new(client, auth);
3005/// // You can configure optional parameters by calling the respective setters at will, and
3006/// // execute the final call using `doit()`.
3007/// // Values shown here are possibly random and not representative !
3008/// let result = hub.voices().list()
3009/// .language_code("ipsum")
3010/// .doit().await;
3011/// # }
3012/// ```
3013pub struct VoiceListCall<'a, C>
3014where
3015 C: 'a,
3016{
3017 hub: &'a Texttospeech<C>,
3018 _language_code: Option<String>,
3019 _delegate: Option<&'a mut dyn common::Delegate>,
3020 _additional_params: HashMap<String, String>,
3021 _scopes: BTreeSet<String>,
3022}
3023
3024impl<'a, C> common::CallBuilder for VoiceListCall<'a, C> {}
3025
3026impl<'a, C> VoiceListCall<'a, C>
3027where
3028 C: common::Connector,
3029{
3030 /// Perform the operation you have build so far.
3031 pub async fn doit(mut self) -> common::Result<(common::Response, ListVoicesResponse)> {
3032 use std::borrow::Cow;
3033 use std::io::{Read, Seek};
3034
3035 use common::{url::Params, ToParts};
3036 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
3037
3038 let mut dd = common::DefaultDelegate;
3039 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
3040 dlg.begin(common::MethodInfo {
3041 id: "texttospeech.voices.list",
3042 http_method: hyper::Method::GET,
3043 });
3044
3045 for &field in ["alt", "languageCode"].iter() {
3046 if self._additional_params.contains_key(field) {
3047 dlg.finished(false);
3048 return Err(common::Error::FieldClash(field));
3049 }
3050 }
3051
3052 let mut params = Params::with_capacity(3 + self._additional_params.len());
3053 if let Some(value) = self._language_code.as_ref() {
3054 params.push("languageCode", value);
3055 }
3056
3057 params.extend(self._additional_params.iter());
3058
3059 params.push("alt", "json");
3060 let mut url = self.hub._base_url.clone() + "v1/voices";
3061 if self._scopes.is_empty() {
3062 self._scopes
3063 .insert(Scope::CloudPlatform.as_ref().to_string());
3064 }
3065
3066 let url = params.parse_with_url(&url);
3067
3068 loop {
3069 let token = match self
3070 .hub
3071 .auth
3072 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
3073 .await
3074 {
3075 Ok(token) => token,
3076 Err(e) => match dlg.token(e) {
3077 Ok(token) => token,
3078 Err(e) => {
3079 dlg.finished(false);
3080 return Err(common::Error::MissingToken(e));
3081 }
3082 },
3083 };
3084 let mut req_result = {
3085 let client = &self.hub.client;
3086 dlg.pre_request();
3087 let mut req_builder = hyper::Request::builder()
3088 .method(hyper::Method::GET)
3089 .uri(url.as_str())
3090 .header(USER_AGENT, self.hub._user_agent.clone());
3091
3092 if let Some(token) = token.as_ref() {
3093 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
3094 }
3095
3096 let request = req_builder
3097 .header(CONTENT_LENGTH, 0_u64)
3098 .body(common::to_body::<String>(None));
3099
3100 client.request(request.unwrap()).await
3101 };
3102
3103 match req_result {
3104 Err(err) => {
3105 if let common::Retry::After(d) = dlg.http_error(&err) {
3106 sleep(d).await;
3107 continue;
3108 }
3109 dlg.finished(false);
3110 return Err(common::Error::HttpError(err));
3111 }
3112 Ok(res) => {
3113 let (mut parts, body) = res.into_parts();
3114 let mut body = common::Body::new(body);
3115 if !parts.status.is_success() {
3116 let bytes = common::to_bytes(body).await.unwrap_or_default();
3117 let error = serde_json::from_str(&common::to_string(&bytes));
3118 let response = common::to_response(parts, bytes.into());
3119
3120 if let common::Retry::After(d) =
3121 dlg.http_failure(&response, error.as_ref().ok())
3122 {
3123 sleep(d).await;
3124 continue;
3125 }
3126
3127 dlg.finished(false);
3128
3129 return Err(match error {
3130 Ok(value) => common::Error::BadRequest(value),
3131 _ => common::Error::Failure(response),
3132 });
3133 }
3134 let response = {
3135 let bytes = common::to_bytes(body).await.unwrap_or_default();
3136 let encoded = common::to_string(&bytes);
3137 match serde_json::from_str(&encoded) {
3138 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
3139 Err(error) => {
3140 dlg.response_json_decode_error(&encoded, &error);
3141 return Err(common::Error::JsonDecodeError(
3142 encoded.to_string(),
3143 error,
3144 ));
3145 }
3146 }
3147 };
3148
3149 dlg.finished(true);
3150 return Ok(response);
3151 }
3152 }
3153 }
3154 }
3155
3156 /// Optional. Recommended. [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag. If not specified, the API will return all supported voices. If specified, the ListVoices call will only return voices that can be used to synthesize this language_code. For example, if you specify `"en-NZ"`, all `"en-NZ"` voices will be returned. If you specify `"no"`, both `"no-\*"` (Norwegian) and `"nb-\*"` (Norwegian Bokmal) voices will be returned.
3157 ///
3158 /// Sets the *language code* query property to the given value.
3159 pub fn language_code(mut self, new_value: &str) -> VoiceListCall<'a, C> {
3160 self._language_code = Some(new_value.to_string());
3161 self
3162 }
3163 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
3164 /// while executing the actual API request.
3165 ///
3166 /// ````text
3167 /// It should be used to handle progress information, and to implement a certain level of resilience.
3168 /// ````
3169 ///
3170 /// Sets the *delegate* property to the given value.
3171 pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> VoiceListCall<'a, C> {
3172 self._delegate = Some(new_value);
3173 self
3174 }
3175
3176 /// Set any additional parameter of the query string used in the request.
3177 /// It should be used to set parameters which are not yet available through their own
3178 /// setters.
3179 ///
3180 /// Please note that this method must not be used to set any of the known parameters
3181 /// which have their own setter method. If done anyway, the request will fail.
3182 ///
3183 /// # Additional Parameters
3184 ///
3185 /// * *$.xgafv* (query-string) - V1 error format.
3186 /// * *access_token* (query-string) - OAuth access token.
3187 /// * *alt* (query-string) - Data format for response.
3188 /// * *callback* (query-string) - JSONP
3189 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
3190 /// * *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.
3191 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
3192 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
3193 /// * *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.
3194 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
3195 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
3196 pub fn param<T>(mut self, name: T, value: T) -> VoiceListCall<'a, C>
3197 where
3198 T: AsRef<str>,
3199 {
3200 self._additional_params
3201 .insert(name.as_ref().to_string(), value.as_ref().to_string());
3202 self
3203 }
3204
3205 /// Identifies the authorization scope for the method you are building.
3206 ///
3207 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
3208 /// [`Scope::CloudPlatform`].
3209 ///
3210 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
3211 /// tokens for more than one scope.
3212 ///
3213 /// Usually there is more than one suitable scope to authorize an operation, some of which may
3214 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
3215 /// sufficient, a read-write scope will do as well.
3216 pub fn add_scope<St>(mut self, scope: St) -> VoiceListCall<'a, C>
3217 where
3218 St: AsRef<str>,
3219 {
3220 self._scopes.insert(String::from(scope.as_ref()));
3221 self
3222 }
3223 /// Identifies the authorization scope(s) for the method you are building.
3224 ///
3225 /// See [`Self::add_scope()`] for details.
3226 pub fn add_scopes<I, St>(mut self, scopes: I) -> VoiceListCall<'a, C>
3227 where
3228 I: IntoIterator<Item = St>,
3229 St: AsRef<str>,
3230 {
3231 self._scopes
3232 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
3233 self
3234 }
3235
3236 /// Removes all scopes, and no default scope will be used either.
3237 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
3238 /// for details).
3239 pub fn clear_scopes(mut self) -> VoiceListCall<'a, C> {
3240 self._scopes.clear();
3241 self
3242 }
3243}