google_speech1_beta1/
api.rs

1#![allow(clippy::ptr_arg)]
2
3use std::collections::{BTreeSet, HashMap};
4
5use tokio::time::sleep;
6
7// ##############
8// UTILITIES ###
9// ############
10
11/// Identifies the an OAuth2 authorization scope.
12/// A scope is needed when requesting an
13/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
14#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
15pub enum Scope {
16    /// View and manage your data across Google Cloud Platform services
17    CloudPlatform,
18}
19
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 Speech 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_speech1_beta1 as speech1_beta1;
49/// use speech1_beta1::{Result, Error};
50/// # async fn dox() {
51/// use speech1_beta1::{Speech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
52///
53/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
54/// // `client_secret`, among other things.
55/// let secret: yup_oauth2::ApplicationSecret = Default::default();
56/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
57/// // unless you replace  `None` with the desired Flow.
58/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
59/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
60/// // retrieve them from storage.
61/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
62///     secret,
63///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
64/// ).build().await.unwrap();
65///
66/// let client = hyper_util::client::legacy::Client::builder(
67///     hyper_util::rt::TokioExecutor::new()
68/// )
69/// .build(
70///     hyper_rustls::HttpsConnectorBuilder::new()
71///         .with_native_roots()
72///         .unwrap()
73///         .https_or_http()
74///         .enable_http1()
75///         .build()
76/// );
77/// let mut hub = Speech::new(client, auth);
78/// // You can configure optional parameters by calling the respective setters at will, and
79/// // execute the final call using `doit()`.
80/// // Values shown here are possibly random and not representative !
81/// let result = hub.operations().list()
82///              .page_token("amet.")
83///              .page_size(-59)
84///              .name("amet.")
85///              .filter("duo")
86///              .doit().await;
87///
88/// match result {
89///     Err(e) => match e {
90///         // The Error enum provides details about what exactly happened.
91///         // You can also just use its `Debug`, `Display` or `Error` traits
92///          Error::HttpError(_)
93///         |Error::Io(_)
94///         |Error::MissingAPIKey
95///         |Error::MissingToken(_)
96///         |Error::Cancelled
97///         |Error::UploadSizeLimitExceeded(_, _)
98///         |Error::Failure(_)
99///         |Error::BadRequest(_)
100///         |Error::FieldClash(_)
101///         |Error::JsonDecodeError(_, _) => println!("{}", e),
102///     },
103///     Ok(res) => println!("Success: {:?}", res),
104/// }
105/// # }
106/// ```
107#[derive(Clone)]
108pub struct Speech<C> {
109    pub client: common::Client<C>,
110    pub auth: Box<dyn common::GetToken>,
111    _user_agent: String,
112    _base_url: String,
113    _root_url: String,
114}
115
116impl<C> common::Hub for Speech<C> {}
117
118impl<'a, C> Speech<C> {
119    pub fn new<A: 'static + common::GetToken>(client: common::Client<C>, auth: A) -> Speech<C> {
120        Speech {
121            client,
122            auth: Box::new(auth),
123            _user_agent: "google-api-rust-client/6.0.0".to_string(),
124            _base_url: "https://speech.googleapis.com/".to_string(),
125            _root_url: "https://speech.googleapis.com/".to_string(),
126        }
127    }
128
129    pub fn operations(&'a self) -> OperationMethods<'a, C> {
130        OperationMethods { hub: self }
131    }
132    pub fn speech(&'a self) -> SpeechMethods<'a, C> {
133        SpeechMethods { hub: self }
134    }
135
136    /// Set the user-agent header field to use in all requests to the server.
137    /// It defaults to `google-api-rust-client/6.0.0`.
138    ///
139    /// Returns the previously set user-agent.
140    pub fn user_agent(&mut self, agent_name: String) -> String {
141        std::mem::replace(&mut self._user_agent, agent_name)
142    }
143
144    /// Set the base url to use in all requests to the server.
145    /// It defaults to `https://speech.googleapis.com/`.
146    ///
147    /// Returns the previously set base url.
148    pub fn base_url(&mut self, new_base_url: String) -> String {
149        std::mem::replace(&mut self._base_url, new_base_url)
150    }
151
152    /// Set the root url to use in all requests to the server.
153    /// It defaults to `https://speech.googleapis.com/`.
154    ///
155    /// Returns the previously set root url.
156    pub fn root_url(&mut self, new_root_url: String) -> String {
157        std::mem::replace(&mut self._root_url, new_root_url)
158    }
159}
160
161// ############
162// SCHEMAS ###
163// ##########
164/// This resource represents a long-running operation that is the result of a
165/// network API call.
166///
167/// # Activities
168///
169/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
170/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
171///
172/// * [list operations](OperationListCall) (none)
173/// * [get operations](OperationGetCall) (response)
174/// * [asyncrecognize speech](SpeechAsyncrecognizeCall) (response)
175#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
176#[serde_with::serde_as]
177#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
178pub struct Operation {
179    /// If the value is `false`, it means the operation is still in progress.
180    /// If `true`, the operation is completed, and either `error` or `response` is
181    /// available.
182    pub done: Option<bool>,
183    /// The normal response of the operation in case of success.  If the original
184    /// method returns no data on success, such as `Delete`, the response is
185    /// `google.protobuf.Empty`.  If the original method is standard
186    /// `Get`/`Create`/`Update`, the response should be the resource.  For other
187    /// methods, the response should have the type `XxxResponse`, where `Xxx`
188    /// is the original method name.  For example, if the original method name
189    /// is `TakeSnapshot()`, the inferred response type is
190    /// `TakeSnapshotResponse`.
191    pub response: Option<HashMap<String, serde_json::Value>>,
192    /// The server-assigned name, which is only unique within the same service that
193    /// originally returns it. If you use the default HTTP mapping, the
194    /// `name` should have the format of `operations/some/unique/name`.
195    pub name: Option<String>,
196    /// The error result of the operation in case of failure or cancellation.
197    pub error: Option<Status>,
198    /// Service-specific metadata associated with the operation.  It typically
199    /// contains progress information and common metadata such as create time.
200    /// Some services might not provide such metadata.  Any method that returns a
201    /// long-running operation should document the metadata type, if any.
202    pub metadata: Option<HashMap<String, serde_json::Value>>,
203}
204
205impl common::Resource for Operation {}
206impl common::ResponseResult for Operation {}
207
208/// The response message for Operations.ListOperations.
209///
210/// # Activities
211///
212/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
213/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
214///
215/// * [list operations](OperationListCall) (response)
216#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
217#[serde_with::serde_as]
218#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
219pub struct ListOperationsResponse {
220    /// The standard List next-page token.
221    #[serde(rename = "nextPageToken")]
222    pub next_page_token: Option<String>,
223    /// A list of operations that matches the specified filter in the request.
224    pub operations: Option<Vec<Operation>>,
225}
226
227impl common::ResponseResult for ListOperationsResponse {}
228
229/// Provides "hints" to the speech recognizer to favor specific words and phrases
230/// in the results.
231///
232/// This type is not used in any activity, and only used as *part* of another schema.
233///
234#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
235#[serde_with::serde_as]
236#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
237pub struct SpeechContext {
238    /// *Optional* A list of strings containing words and phrases "hints" so that
239    /// the speech recognition is more likely to recognize them. This can be used
240    /// to improve the accuracy for specific words and phrases, for example, if
241    /// specific commands are typically spoken by the user. This can also be used
242    /// to add additional words to the vocabulary of the recognizer. See
243    /// [usage limits](https://cloud.google.com/speech/limits#content).
244    pub phrases: Option<Vec<String>>,
245}
246
247impl common::Part for SpeechContext {}
248
249/// Alternative hypotheses (a.k.a. n-best list).
250///
251/// This type is not used in any activity, and only used as *part* of another schema.
252///
253#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
254#[serde_with::serde_as]
255#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
256pub struct SpeechRecognitionAlternative {
257    /// *Output-only* The confidence estimate between 0.0 and 1.0. A higher number
258    /// indicates an estimated greater likelihood that the recognized words are
259    /// correct. This field is typically provided only for the top hypothesis, and
260    /// only for `is_final=true` results. Clients should not rely on the
261    /// `confidence` field as it is not guaranteed to be accurate, or even set, in
262    /// any of the results.
263    /// The default of 0.0 is a sentinel value indicating `confidence` was not set.
264    pub confidence: Option<f32>,
265    /// *Output-only* Transcript text representing the words that the user spoke.
266    pub transcript: Option<String>,
267}
268
269impl common::Part for SpeechRecognitionAlternative {}
270
271/// A speech recognition result corresponding to a portion of the audio.
272///
273/// This type is not used in any activity, and only used as *part* of another schema.
274///
275#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
276#[serde_with::serde_as]
277#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
278pub struct SpeechRecognitionResult {
279    /// *Output-only* May contain one or more recognition hypotheses (up to the
280    /// maximum specified in `max_alternatives`).
281    pub alternatives: Option<Vec<SpeechRecognitionAlternative>>,
282}
283
284impl common::Part for SpeechRecognitionResult {}
285
286/// Provides information to the recognizer that specifies how to process the
287/// request.
288///
289/// This type is not used in any activity, and only used as *part* of another schema.
290///
291#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
292#[serde_with::serde_as]
293#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
294pub struct RecognitionConfig {
295    /// *Optional* Maximum number of recognition hypotheses to be returned.
296    /// Specifically, the maximum number of `SpeechRecognitionAlternative` messages
297    /// within each `SpeechRecognitionResult`.
298    /// The server may return fewer than `max_alternatives`.
299    /// Valid values are `0`-`30`. A value of `0` or `1` will return a maximum of
300    /// one. If omitted, will return a maximum of one.
301    #[serde(rename = "maxAlternatives")]
302    pub max_alternatives: Option<i32>,
303    /// *Required* Sample rate in Hertz of the audio data sent in all
304    /// `RecognitionAudio` messages. Valid values are: 8000-48000.
305    /// 16000 is optimal. For best results, set the sampling rate of the audio
306    /// source to 16000 Hz. If that's not possible, use the native sample rate of
307    /// the audio source (instead of re-sampling).
308    #[serde(rename = "sampleRate")]
309    pub sample_rate: Option<i32>,
310    /// *Optional* The language of the supplied audio as a BCP-47 language tag.
311    /// Example: "en-GB"  https://www.rfc-editor.org/rfc/bcp/bcp47.txt
312    /// If omitted, defaults to "en-US". See
313    /// [Language Support](https://cloud.google.com/speech/docs/languages)
314    /// for a list of the currently supported language codes.
315    #[serde(rename = "languageCode")]
316    pub language_code: Option<String>,
317    /// *Optional* If set to `true`, the server will attempt to filter out
318    /// profanities, replacing all but the initial character in each filtered word
319    /// with asterisks, e.g. "f***". If set to `false` or omitted, profanities
320    /// won't be filtered out.
321    #[serde(rename = "profanityFilter")]
322    pub profanity_filter: Option<bool>,
323    /// *Optional* A means to provide context to assist the speech recognition.
324    #[serde(rename = "speechContext")]
325    pub speech_context: Option<SpeechContext>,
326    /// *Required* Encoding of audio data sent in all `RecognitionAudio` messages.
327    pub encoding: Option<String>,
328}
329
330impl common::Part for RecognitionConfig {}
331
332/// The top-level message sent by the client for the `AsyncRecognize` method.
333///
334/// # Activities
335///
336/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
337/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
338///
339/// * [asyncrecognize speech](SpeechAsyncrecognizeCall) (request)
340#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
341#[serde_with::serde_as]
342#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
343pub struct AsyncRecognizeRequest {
344    /// *Required* Provides information to the recognizer that specifies how to
345    /// process the request.
346    pub config: Option<RecognitionConfig>,
347    /// *Required* The audio data to be recognized.
348    pub audio: Option<RecognitionAudio>,
349}
350
351impl common::RequestValue for AsyncRecognizeRequest {}
352
353/// Contains audio data in the encoding specified in the `RecognitionConfig`.
354/// Either `content` or `uri` must be supplied. Supplying both or neither
355/// returns google.rpc.Code.INVALID_ARGUMENT. See
356/// [audio limits](https://cloud.google.com/speech/limits#content).
357///
358/// This type is not used in any activity, and only used as *part* of another schema.
359///
360#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
361#[serde_with::serde_as]
362#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
363pub struct RecognitionAudio {
364    /// URI that points to a file that contains audio data bytes as specified in
365    /// `RecognitionConfig`. Currently, only Google Cloud Storage URIs are
366    /// supported, which must be specified in the following format:
367    /// `gs://bucket_name/object_name` (other URI formats return
368    /// google.rpc.Code.INVALID_ARGUMENT). For more information, see
369    /// [Request URIs](https://cloud.google.com/storage/docs/reference-uris).
370    pub uri: Option<String>,
371    /// The audio data bytes encoded as specified in
372    /// `RecognitionConfig`. Note: as with all bytes fields, protobuffers use a
373    /// pure binary representation, whereas JSON representations use base64.
374    #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
375    pub content: Option<Vec<u8>>,
376}
377
378impl common::Part for RecognitionAudio {}
379
380/// The top-level message sent by the client for the `SyncRecognize` method.
381///
382/// # Activities
383///
384/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
385/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
386///
387/// * [syncrecognize speech](SpeechSyncrecognizeCall) (request)
388#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
389#[serde_with::serde_as]
390#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
391pub struct SyncRecognizeRequest {
392    /// *Required* Provides information to the recognizer that specifies how to
393    /// process the request.
394    pub config: Option<RecognitionConfig>,
395    /// *Required* The audio data to be recognized.
396    pub audio: Option<RecognitionAudio>,
397}
398
399impl common::RequestValue for SyncRecognizeRequest {}
400
401/// The only message returned to the client by `SyncRecognize`. method. It
402/// contains the result as zero or more sequential `SpeechRecognitionResult`
403/// messages.
404///
405/// # Activities
406///
407/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
408/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
409///
410/// * [syncrecognize speech](SpeechSyncrecognizeCall) (response)
411#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
412#[serde_with::serde_as]
413#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
414pub struct SyncRecognizeResponse {
415    /// *Output-only* Sequential list of transcription results corresponding to
416    /// sequential portions of audio.
417    pub results: Option<Vec<SpeechRecognitionResult>>,
418}
419
420impl common::ResponseResult for SyncRecognizeResponse {}
421
422/// The `Status` type defines a logical error model that is suitable for different
423/// programming environments, including REST APIs and RPC APIs. It is used by
424/// [gRPC](https://github.com/grpc). The error model is designed to be:
425///
426/// * Simple to use and understand for most users
427/// * Flexible enough to meet unexpected needs
428///
429/// # Overview
430///
431/// The `Status` message contains three pieces of data: error code, error message,
432/// and error details. The error code should be an enum value of
433/// google.rpc.Code, but it may accept additional error codes if needed.  The
434/// error message should be a developer-facing English message that helps
435/// developers *understand* and *resolve* the error. If a localized user-facing
436/// error message is needed, put the localized message in the error details or
437/// localize it in the client. The optional error details may contain arbitrary
438/// information about the error. There is a predefined set of error detail types
439/// in the package `google.rpc` that can be used for common error conditions.
440///
441/// # Language mapping
442///
443/// The `Status` message is the logical representation of the error model, but it
444/// is not necessarily the actual wire format. When the `Status` message is
445/// exposed in different client libraries and different wire protocols, it can be
446/// mapped differently. For example, it will likely be mapped to some exceptions
447/// in Java, but more likely mapped to some error codes in C.
448///
449/// # Other uses
450///
451/// The error model and the `Status` message can be used in a variety of
452/// environments, either with or without APIs, to provide a
453/// consistent developer experience across different environments.
454///
455/// Example uses of this error model include:
456///
457/// * Partial errors. If a service needs to return partial errors to the client,
458///   it may embed the `Status` in the normal response to indicate the partial
459///   errors.
460///
461/// * Workflow errors. A typical workflow has multiple steps. Each step may
462///   have a `Status` message for error reporting.
463///
464/// * Batch operations. If a client uses batch request and batch response, the
465///   `Status` message should be used directly inside batch response, one for
466///   each error sub-response.
467///
468/// * Asynchronous operations. If an API call embeds asynchronous operation
469///   results in its response, the status of those operations should be
470///   represented directly using the `Status` message.
471///
472/// * Logging. If some API errors are stored in logs, the message `Status` could
473///   be used directly after any stripping needed for security/privacy reasons.
474///
475/// This type is not used in any activity, and only used as *part* of another schema.
476#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
477#[serde_with::serde_as]
478#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
479pub struct Status {
480    /// A list of messages that carry the error details.  There is a common set of
481    /// message types for APIs to use.
482    pub details: Option<Vec<HashMap<String, serde_json::Value>>>,
483    /// The status code, which should be an enum value of google.rpc.Code.
484    pub code: Option<i32>,
485    /// A developer-facing error message, which should be in English. Any
486    /// user-facing error message should be localized and sent in the
487    /// google.rpc.Status.details field, or localized by the client.
488    pub message: Option<String>,
489}
490
491impl common::Part for Status {}
492
493// ###################
494// MethodBuilders ###
495// #################
496
497/// A builder providing access to all methods supported on *operation* resources.
498/// It is not used directly, but through the [`Speech`] hub.
499///
500/// # Example
501///
502/// Instantiate a resource builder
503///
504/// ```test_harness,no_run
505/// extern crate hyper;
506/// extern crate hyper_rustls;
507/// extern crate google_speech1_beta1 as speech1_beta1;
508///
509/// # async fn dox() {
510/// use speech1_beta1::{Speech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
511///
512/// let secret: yup_oauth2::ApplicationSecret = Default::default();
513/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
514///     secret,
515///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
516/// ).build().await.unwrap();
517///
518/// let client = hyper_util::client::legacy::Client::builder(
519///     hyper_util::rt::TokioExecutor::new()
520/// )
521/// .build(
522///     hyper_rustls::HttpsConnectorBuilder::new()
523///         .with_native_roots()
524///         .unwrap()
525///         .https_or_http()
526///         .enable_http1()
527///         .build()
528/// );
529/// let mut hub = Speech::new(client, auth);
530/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
531/// // like `get(...)` and `list(...)`
532/// // to build up your call.
533/// let rb = hub.operations();
534/// # }
535/// ```
536pub struct OperationMethods<'a, C>
537where
538    C: 'a,
539{
540    hub: &'a Speech<C>,
541}
542
543impl<'a, C> common::MethodsBuilder for OperationMethods<'a, C> {}
544
545impl<'a, C> OperationMethods<'a, C> {
546    /// Create a builder to help you perform the following task:
547    ///
548    /// Lists operations that match the specified filter in the request. If the
549    /// server doesn't support this method, it returns `UNIMPLEMENTED`.
550    ///
551    /// NOTE: the `name` binding allows API services to override the binding
552    /// to use different resource name schemes, such as `users/*/operations`. To
553    /// override the binding, API services can add a binding such as
554    /// `"/v1/{name=users/*}/operations"` to their service configuration.
555    /// For backwards compatibility, the default name includes the operations
556    /// collection id, however overriding users must ensure the name binding
557    /// is the parent resource, without the operations collection id.
558    pub fn list(&self) -> OperationListCall<'a, C> {
559        OperationListCall {
560            hub: self.hub,
561            _page_token: Default::default(),
562            _page_size: Default::default(),
563            _name: Default::default(),
564            _filter: Default::default(),
565            _delegate: Default::default(),
566            _additional_params: Default::default(),
567            _scopes: Default::default(),
568        }
569    }
570
571    /// Create a builder to help you perform the following task:
572    ///
573    /// Gets the latest state of a long-running operation.  Clients can use this
574    /// method to poll the operation result at intervals as recommended by the API
575    /// service.
576    ///
577    /// # Arguments
578    ///
579    /// * `name` - The name of the operation resource.
580    pub fn get(&self, name: &str) -> OperationGetCall<'a, C> {
581        OperationGetCall {
582            hub: self.hub,
583            _name: name.to_string(),
584            _delegate: Default::default(),
585            _additional_params: Default::default(),
586            _scopes: Default::default(),
587        }
588    }
589}
590
591/// A builder providing access to all methods supported on *speech* resources.
592/// It is not used directly, but through the [`Speech`] hub.
593///
594/// # Example
595///
596/// Instantiate a resource builder
597///
598/// ```test_harness,no_run
599/// extern crate hyper;
600/// extern crate hyper_rustls;
601/// extern crate google_speech1_beta1 as speech1_beta1;
602///
603/// # async fn dox() {
604/// use speech1_beta1::{Speech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
605///
606/// let secret: yup_oauth2::ApplicationSecret = Default::default();
607/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
608///     secret,
609///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
610/// ).build().await.unwrap();
611///
612/// let client = hyper_util::client::legacy::Client::builder(
613///     hyper_util::rt::TokioExecutor::new()
614/// )
615/// .build(
616///     hyper_rustls::HttpsConnectorBuilder::new()
617///         .with_native_roots()
618///         .unwrap()
619///         .https_or_http()
620///         .enable_http1()
621///         .build()
622/// );
623/// let mut hub = Speech::new(client, auth);
624/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
625/// // like `asyncrecognize(...)` and `syncrecognize(...)`
626/// // to build up your call.
627/// let rb = hub.speech();
628/// # }
629/// ```
630pub struct SpeechMethods<'a, C>
631where
632    C: 'a,
633{
634    hub: &'a Speech<C>,
635}
636
637impl<'a, C> common::MethodsBuilder for SpeechMethods<'a, C> {}
638
639impl<'a, C> SpeechMethods<'a, C> {
640    /// Create a builder to help you perform the following task:
641    ///
642    /// Performs asynchronous speech recognition: receive results via the
643    /// \[google.longrunning.Operations\]
644    /// (/speech/reference/rest/v1beta1/operations#Operation)
645    /// interface. Returns either an
646    /// `Operation.error` or an `Operation.response` which contains
647    /// an `AsyncRecognizeResponse` message.
648    ///
649    /// # Arguments
650    ///
651    /// * `request` - No description provided.
652    pub fn asyncrecognize(
653        &self,
654        request: AsyncRecognizeRequest,
655    ) -> SpeechAsyncrecognizeCall<'a, C> {
656        SpeechAsyncrecognizeCall {
657            hub: self.hub,
658            _request: request,
659            _delegate: Default::default(),
660            _additional_params: Default::default(),
661            _scopes: Default::default(),
662        }
663    }
664
665    /// Create a builder to help you perform the following task:
666    ///
667    /// Performs synchronous speech recognition: receive results after all audio
668    /// has been sent and processed.
669    ///
670    /// # Arguments
671    ///
672    /// * `request` - No description provided.
673    pub fn syncrecognize(&self, request: SyncRecognizeRequest) -> SpeechSyncrecognizeCall<'a, C> {
674        SpeechSyncrecognizeCall {
675            hub: self.hub,
676            _request: request,
677            _delegate: Default::default(),
678            _additional_params: Default::default(),
679            _scopes: Default::default(),
680        }
681    }
682}
683
684// ###################
685// CallBuilders   ###
686// #################
687
688/// Lists operations that match the specified filter in the request. If the
689/// server doesn't support this method, it returns `UNIMPLEMENTED`.
690///
691/// NOTE: the `name` binding allows API services to override the binding
692/// to use different resource name schemes, such as `users/*/operations`. To
693/// override the binding, API services can add a binding such as
694/// `"/v1/{name=users/*}/operations"` to their service configuration.
695/// For backwards compatibility, the default name includes the operations
696/// collection id, however overriding users must ensure the name binding
697/// is the parent resource, without the operations collection id.
698///
699/// A builder for the *list* method supported by a *operation* resource.
700/// It is not used directly, but through a [`OperationMethods`] instance.
701///
702/// # Example
703///
704/// Instantiate a resource method builder
705///
706/// ```test_harness,no_run
707/// # extern crate hyper;
708/// # extern crate hyper_rustls;
709/// # extern crate google_speech1_beta1 as speech1_beta1;
710/// # async fn dox() {
711/// # use speech1_beta1::{Speech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
712///
713/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
714/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
715/// #     secret,
716/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
717/// # ).build().await.unwrap();
718///
719/// # let client = hyper_util::client::legacy::Client::builder(
720/// #     hyper_util::rt::TokioExecutor::new()
721/// # )
722/// # .build(
723/// #     hyper_rustls::HttpsConnectorBuilder::new()
724/// #         .with_native_roots()
725/// #         .unwrap()
726/// #         .https_or_http()
727/// #         .enable_http1()
728/// #         .build()
729/// # );
730/// # let mut hub = Speech::new(client, auth);
731/// // You can configure optional parameters by calling the respective setters at will, and
732/// // execute the final call using `doit()`.
733/// // Values shown here are possibly random and not representative !
734/// let result = hub.operations().list()
735///              .page_token("ipsum")
736///              .page_size(-62)
737///              .name("Lorem")
738///              .filter("gubergren")
739///              .doit().await;
740/// # }
741/// ```
742pub struct OperationListCall<'a, C>
743where
744    C: 'a,
745{
746    hub: &'a Speech<C>,
747    _page_token: Option<String>,
748    _page_size: Option<i32>,
749    _name: Option<String>,
750    _filter: Option<String>,
751    _delegate: Option<&'a mut dyn common::Delegate>,
752    _additional_params: HashMap<String, String>,
753    _scopes: BTreeSet<String>,
754}
755
756impl<'a, C> common::CallBuilder for OperationListCall<'a, C> {}
757
758impl<'a, C> OperationListCall<'a, C>
759where
760    C: common::Connector,
761{
762    /// Perform the operation you have build so far.
763    pub async fn doit(mut self) -> common::Result<(common::Response, ListOperationsResponse)> {
764        use std::borrow::Cow;
765        use std::io::{Read, Seek};
766
767        use common::{url::Params, ToParts};
768        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
769
770        let mut dd = common::DefaultDelegate;
771        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
772        dlg.begin(common::MethodInfo {
773            id: "speech.operations.list",
774            http_method: hyper::Method::GET,
775        });
776
777        for &field in ["alt", "pageToken", "pageSize", "name", "filter"].iter() {
778            if self._additional_params.contains_key(field) {
779                dlg.finished(false);
780                return Err(common::Error::FieldClash(field));
781            }
782        }
783
784        let mut params = Params::with_capacity(6 + self._additional_params.len());
785        if let Some(value) = self._page_token.as_ref() {
786            params.push("pageToken", value);
787        }
788        if let Some(value) = self._page_size.as_ref() {
789            params.push("pageSize", value.to_string());
790        }
791        if let Some(value) = self._name.as_ref() {
792            params.push("name", value);
793        }
794        if let Some(value) = self._filter.as_ref() {
795            params.push("filter", value);
796        }
797
798        params.extend(self._additional_params.iter());
799
800        params.push("alt", "json");
801        let mut url = self.hub._base_url.clone() + "v1beta1/operations";
802        if self._scopes.is_empty() {
803            self._scopes
804                .insert(Scope::CloudPlatform.as_ref().to_string());
805        }
806
807        let url = params.parse_with_url(&url);
808
809        loop {
810            let token = match self
811                .hub
812                .auth
813                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
814                .await
815            {
816                Ok(token) => token,
817                Err(e) => match dlg.token(e) {
818                    Ok(token) => token,
819                    Err(e) => {
820                        dlg.finished(false);
821                        return Err(common::Error::MissingToken(e));
822                    }
823                },
824            };
825            let mut req_result = {
826                let client = &self.hub.client;
827                dlg.pre_request();
828                let mut req_builder = hyper::Request::builder()
829                    .method(hyper::Method::GET)
830                    .uri(url.as_str())
831                    .header(USER_AGENT, self.hub._user_agent.clone());
832
833                if let Some(token) = token.as_ref() {
834                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
835                }
836
837                let request = req_builder
838                    .header(CONTENT_LENGTH, 0_u64)
839                    .body(common::to_body::<String>(None));
840
841                client.request(request.unwrap()).await
842            };
843
844            match req_result {
845                Err(err) => {
846                    if let common::Retry::After(d) = dlg.http_error(&err) {
847                        sleep(d).await;
848                        continue;
849                    }
850                    dlg.finished(false);
851                    return Err(common::Error::HttpError(err));
852                }
853                Ok(res) => {
854                    let (mut parts, body) = res.into_parts();
855                    let mut body = common::Body::new(body);
856                    if !parts.status.is_success() {
857                        let bytes = common::to_bytes(body).await.unwrap_or_default();
858                        let error = serde_json::from_str(&common::to_string(&bytes));
859                        let response = common::to_response(parts, bytes.into());
860
861                        if let common::Retry::After(d) =
862                            dlg.http_failure(&response, error.as_ref().ok())
863                        {
864                            sleep(d).await;
865                            continue;
866                        }
867
868                        dlg.finished(false);
869
870                        return Err(match error {
871                            Ok(value) => common::Error::BadRequest(value),
872                            _ => common::Error::Failure(response),
873                        });
874                    }
875                    let response = {
876                        let bytes = common::to_bytes(body).await.unwrap_or_default();
877                        let encoded = common::to_string(&bytes);
878                        match serde_json::from_str(&encoded) {
879                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
880                            Err(error) => {
881                                dlg.response_json_decode_error(&encoded, &error);
882                                return Err(common::Error::JsonDecodeError(
883                                    encoded.to_string(),
884                                    error,
885                                ));
886                            }
887                        }
888                    };
889
890                    dlg.finished(true);
891                    return Ok(response);
892                }
893            }
894        }
895    }
896
897    /// The standard list page token.
898    ///
899    /// Sets the *page token* query property to the given value.
900    pub fn page_token(mut self, new_value: &str) -> OperationListCall<'a, C> {
901        self._page_token = Some(new_value.to_string());
902        self
903    }
904    /// The standard list page size.
905    ///
906    /// Sets the *page size* query property to the given value.
907    pub fn page_size(mut self, new_value: i32) -> OperationListCall<'a, C> {
908        self._page_size = Some(new_value);
909        self
910    }
911    /// The name of the operation's parent resource.
912    ///
913    /// Sets the *name* query property to the given value.
914    pub fn name(mut self, new_value: &str) -> OperationListCall<'a, C> {
915        self._name = Some(new_value.to_string());
916        self
917    }
918    /// The standard list filter.
919    ///
920    /// Sets the *filter* query property to the given value.
921    pub fn filter(mut self, new_value: &str) -> OperationListCall<'a, C> {
922        self._filter = Some(new_value.to_string());
923        self
924    }
925    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
926    /// while executing the actual API request.
927    ///
928    /// ````text
929    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
930    /// ````
931    ///
932    /// Sets the *delegate* property to the given value.
933    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> OperationListCall<'a, C> {
934        self._delegate = Some(new_value);
935        self
936    }
937
938    /// Set any additional parameter of the query string used in the request.
939    /// It should be used to set parameters which are not yet available through their own
940    /// setters.
941    ///
942    /// Please note that this method must not be used to set any of the known parameters
943    /// which have their own setter method. If done anyway, the request will fail.
944    ///
945    /// # Additional Parameters
946    ///
947    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
948    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
949    /// * *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.
950    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
951    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
952    /// * *callback* (query-string) - JSONP
953    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
954    /// * *$.xgafv* (query-string) - V1 error format.
955    /// * *alt* (query-string) - Data format for response.
956    /// * *access_token* (query-string) - OAuth access token.
957    /// * *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.
958    pub fn param<T>(mut self, name: T, value: T) -> OperationListCall<'a, C>
959    where
960        T: AsRef<str>,
961    {
962        self._additional_params
963            .insert(name.as_ref().to_string(), value.as_ref().to_string());
964        self
965    }
966
967    /// Identifies the authorization scope for the method you are building.
968    ///
969    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
970    /// [`Scope::CloudPlatform`].
971    ///
972    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
973    /// tokens for more than one scope.
974    ///
975    /// Usually there is more than one suitable scope to authorize an operation, some of which may
976    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
977    /// sufficient, a read-write scope will do as well.
978    pub fn add_scope<St>(mut self, scope: St) -> OperationListCall<'a, C>
979    where
980        St: AsRef<str>,
981    {
982        self._scopes.insert(String::from(scope.as_ref()));
983        self
984    }
985    /// Identifies the authorization scope(s) for the method you are building.
986    ///
987    /// See [`Self::add_scope()`] for details.
988    pub fn add_scopes<I, St>(mut self, scopes: I) -> OperationListCall<'a, C>
989    where
990        I: IntoIterator<Item = St>,
991        St: AsRef<str>,
992    {
993        self._scopes
994            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
995        self
996    }
997
998    /// Removes all scopes, and no default scope will be used either.
999    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1000    /// for details).
1001    pub fn clear_scopes(mut self) -> OperationListCall<'a, C> {
1002        self._scopes.clear();
1003        self
1004    }
1005}
1006
1007/// Gets the latest state of a long-running operation.  Clients can use this
1008/// method to poll the operation result at intervals as recommended by the API
1009/// service.
1010///
1011/// A builder for the *get* method supported by a *operation* resource.
1012/// It is not used directly, but through a [`OperationMethods`] instance.
1013///
1014/// # Example
1015///
1016/// Instantiate a resource method builder
1017///
1018/// ```test_harness,no_run
1019/// # extern crate hyper;
1020/// # extern crate hyper_rustls;
1021/// # extern crate google_speech1_beta1 as speech1_beta1;
1022/// # async fn dox() {
1023/// # use speech1_beta1::{Speech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1024///
1025/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1026/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1027/// #     secret,
1028/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1029/// # ).build().await.unwrap();
1030///
1031/// # let client = hyper_util::client::legacy::Client::builder(
1032/// #     hyper_util::rt::TokioExecutor::new()
1033/// # )
1034/// # .build(
1035/// #     hyper_rustls::HttpsConnectorBuilder::new()
1036/// #         .with_native_roots()
1037/// #         .unwrap()
1038/// #         .https_or_http()
1039/// #         .enable_http1()
1040/// #         .build()
1041/// # );
1042/// # let mut hub = Speech::new(client, auth);
1043/// // You can configure optional parameters by calling the respective setters at will, and
1044/// // execute the final call using `doit()`.
1045/// // Values shown here are possibly random and not representative !
1046/// let result = hub.operations().get("name")
1047///              .doit().await;
1048/// # }
1049/// ```
1050pub struct OperationGetCall<'a, C>
1051where
1052    C: 'a,
1053{
1054    hub: &'a Speech<C>,
1055    _name: String,
1056    _delegate: Option<&'a mut dyn common::Delegate>,
1057    _additional_params: HashMap<String, String>,
1058    _scopes: BTreeSet<String>,
1059}
1060
1061impl<'a, C> common::CallBuilder for OperationGetCall<'a, C> {}
1062
1063impl<'a, C> OperationGetCall<'a, C>
1064where
1065    C: common::Connector,
1066{
1067    /// Perform the operation you have build so far.
1068    pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
1069        use std::borrow::Cow;
1070        use std::io::{Read, Seek};
1071
1072        use common::{url::Params, ToParts};
1073        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1074
1075        let mut dd = common::DefaultDelegate;
1076        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1077        dlg.begin(common::MethodInfo {
1078            id: "speech.operations.get",
1079            http_method: hyper::Method::GET,
1080        });
1081
1082        for &field in ["alt", "name"].iter() {
1083            if self._additional_params.contains_key(field) {
1084                dlg.finished(false);
1085                return Err(common::Error::FieldClash(field));
1086            }
1087        }
1088
1089        let mut params = Params::with_capacity(3 + self._additional_params.len());
1090        params.push("name", self._name);
1091
1092        params.extend(self._additional_params.iter());
1093
1094        params.push("alt", "json");
1095        let mut url = self.hub._base_url.clone() + "v1beta1/operations/{+name}";
1096        if self._scopes.is_empty() {
1097            self._scopes
1098                .insert(Scope::CloudPlatform.as_ref().to_string());
1099        }
1100
1101        #[allow(clippy::single_element_loop)]
1102        for &(find_this, param_name) in [("{+name}", "name")].iter() {
1103            url = params.uri_replacement(url, param_name, find_this, true);
1104        }
1105        {
1106            let to_remove = ["name"];
1107            params.remove_params(&to_remove);
1108        }
1109
1110        let url = params.parse_with_url(&url);
1111
1112        loop {
1113            let token = match self
1114                .hub
1115                .auth
1116                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1117                .await
1118            {
1119                Ok(token) => token,
1120                Err(e) => match dlg.token(e) {
1121                    Ok(token) => token,
1122                    Err(e) => {
1123                        dlg.finished(false);
1124                        return Err(common::Error::MissingToken(e));
1125                    }
1126                },
1127            };
1128            let mut req_result = {
1129                let client = &self.hub.client;
1130                dlg.pre_request();
1131                let mut req_builder = hyper::Request::builder()
1132                    .method(hyper::Method::GET)
1133                    .uri(url.as_str())
1134                    .header(USER_AGENT, self.hub._user_agent.clone());
1135
1136                if let Some(token) = token.as_ref() {
1137                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1138                }
1139
1140                let request = req_builder
1141                    .header(CONTENT_LENGTH, 0_u64)
1142                    .body(common::to_body::<String>(None));
1143
1144                client.request(request.unwrap()).await
1145            };
1146
1147            match req_result {
1148                Err(err) => {
1149                    if let common::Retry::After(d) = dlg.http_error(&err) {
1150                        sleep(d).await;
1151                        continue;
1152                    }
1153                    dlg.finished(false);
1154                    return Err(common::Error::HttpError(err));
1155                }
1156                Ok(res) => {
1157                    let (mut parts, body) = res.into_parts();
1158                    let mut body = common::Body::new(body);
1159                    if !parts.status.is_success() {
1160                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1161                        let error = serde_json::from_str(&common::to_string(&bytes));
1162                        let response = common::to_response(parts, bytes.into());
1163
1164                        if let common::Retry::After(d) =
1165                            dlg.http_failure(&response, error.as_ref().ok())
1166                        {
1167                            sleep(d).await;
1168                            continue;
1169                        }
1170
1171                        dlg.finished(false);
1172
1173                        return Err(match error {
1174                            Ok(value) => common::Error::BadRequest(value),
1175                            _ => common::Error::Failure(response),
1176                        });
1177                    }
1178                    let response = {
1179                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1180                        let encoded = common::to_string(&bytes);
1181                        match serde_json::from_str(&encoded) {
1182                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1183                            Err(error) => {
1184                                dlg.response_json_decode_error(&encoded, &error);
1185                                return Err(common::Error::JsonDecodeError(
1186                                    encoded.to_string(),
1187                                    error,
1188                                ));
1189                            }
1190                        }
1191                    };
1192
1193                    dlg.finished(true);
1194                    return Ok(response);
1195                }
1196            }
1197        }
1198    }
1199
1200    /// The name of the operation resource.
1201    ///
1202    /// Sets the *name* path property to the given value.
1203    ///
1204    /// Even though the property as already been set when instantiating this call,
1205    /// we provide this method for API completeness.
1206    pub fn name(mut self, new_value: &str) -> OperationGetCall<'a, C> {
1207        self._name = new_value.to_string();
1208        self
1209    }
1210    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1211    /// while executing the actual API request.
1212    ///
1213    /// ````text
1214    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1215    /// ````
1216    ///
1217    /// Sets the *delegate* property to the given value.
1218    pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> OperationGetCall<'a, C> {
1219        self._delegate = Some(new_value);
1220        self
1221    }
1222
1223    /// Set any additional parameter of the query string used in the request.
1224    /// It should be used to set parameters which are not yet available through their own
1225    /// setters.
1226    ///
1227    /// Please note that this method must not be used to set any of the known parameters
1228    /// which have their own setter method. If done anyway, the request will fail.
1229    ///
1230    /// # Additional Parameters
1231    ///
1232    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1233    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1234    /// * *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.
1235    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1236    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1237    /// * *callback* (query-string) - JSONP
1238    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1239    /// * *$.xgafv* (query-string) - V1 error format.
1240    /// * *alt* (query-string) - Data format for response.
1241    /// * *access_token* (query-string) - OAuth access token.
1242    /// * *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.
1243    pub fn param<T>(mut self, name: T, value: T) -> OperationGetCall<'a, C>
1244    where
1245        T: AsRef<str>,
1246    {
1247        self._additional_params
1248            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1249        self
1250    }
1251
1252    /// Identifies the authorization scope for the method you are building.
1253    ///
1254    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1255    /// [`Scope::CloudPlatform`].
1256    ///
1257    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1258    /// tokens for more than one scope.
1259    ///
1260    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1261    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1262    /// sufficient, a read-write scope will do as well.
1263    pub fn add_scope<St>(mut self, scope: St) -> OperationGetCall<'a, C>
1264    where
1265        St: AsRef<str>,
1266    {
1267        self._scopes.insert(String::from(scope.as_ref()));
1268        self
1269    }
1270    /// Identifies the authorization scope(s) for the method you are building.
1271    ///
1272    /// See [`Self::add_scope()`] for details.
1273    pub fn add_scopes<I, St>(mut self, scopes: I) -> OperationGetCall<'a, C>
1274    where
1275        I: IntoIterator<Item = St>,
1276        St: AsRef<str>,
1277    {
1278        self._scopes
1279            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1280        self
1281    }
1282
1283    /// Removes all scopes, and no default scope will be used either.
1284    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1285    /// for details).
1286    pub fn clear_scopes(mut self) -> OperationGetCall<'a, C> {
1287        self._scopes.clear();
1288        self
1289    }
1290}
1291
1292/// Performs asynchronous speech recognition: receive results via the
1293/// \[google.longrunning.Operations\]
1294/// (/speech/reference/rest/v1beta1/operations#Operation)
1295/// interface. Returns either an
1296/// `Operation.error` or an `Operation.response` which contains
1297/// an `AsyncRecognizeResponse` message.
1298///
1299/// A builder for the *asyncrecognize* method supported by a *speech* resource.
1300/// It is not used directly, but through a [`SpeechMethods`] instance.
1301///
1302/// # Example
1303///
1304/// Instantiate a resource method builder
1305///
1306/// ```test_harness,no_run
1307/// # extern crate hyper;
1308/// # extern crate hyper_rustls;
1309/// # extern crate google_speech1_beta1 as speech1_beta1;
1310/// use speech1_beta1::api::AsyncRecognizeRequest;
1311/// # async fn dox() {
1312/// # use speech1_beta1::{Speech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1313///
1314/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1315/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1316/// #     secret,
1317/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1318/// # ).build().await.unwrap();
1319///
1320/// # let client = hyper_util::client::legacy::Client::builder(
1321/// #     hyper_util::rt::TokioExecutor::new()
1322/// # )
1323/// # .build(
1324/// #     hyper_rustls::HttpsConnectorBuilder::new()
1325/// #         .with_native_roots()
1326/// #         .unwrap()
1327/// #         .https_or_http()
1328/// #         .enable_http1()
1329/// #         .build()
1330/// # );
1331/// # let mut hub = Speech::new(client, auth);
1332/// // As the method needs a request, you would usually fill it with the desired information
1333/// // into the respective structure. Some of the parts shown here might not be applicable !
1334/// // Values shown here are possibly random and not representative !
1335/// let mut req = AsyncRecognizeRequest::default();
1336///
1337/// // You can configure optional parameters by calling the respective setters at will, and
1338/// // execute the final call using `doit()`.
1339/// // Values shown here are possibly random and not representative !
1340/// let result = hub.speech().asyncrecognize(req)
1341///              .doit().await;
1342/// # }
1343/// ```
1344pub struct SpeechAsyncrecognizeCall<'a, C>
1345where
1346    C: 'a,
1347{
1348    hub: &'a Speech<C>,
1349    _request: AsyncRecognizeRequest,
1350    _delegate: Option<&'a mut dyn common::Delegate>,
1351    _additional_params: HashMap<String, String>,
1352    _scopes: BTreeSet<String>,
1353}
1354
1355impl<'a, C> common::CallBuilder for SpeechAsyncrecognizeCall<'a, C> {}
1356
1357impl<'a, C> SpeechAsyncrecognizeCall<'a, C>
1358where
1359    C: common::Connector,
1360{
1361    /// Perform the operation you have build so far.
1362    pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
1363        use std::borrow::Cow;
1364        use std::io::{Read, Seek};
1365
1366        use common::{url::Params, ToParts};
1367        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1368
1369        let mut dd = common::DefaultDelegate;
1370        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1371        dlg.begin(common::MethodInfo {
1372            id: "speech.speech.asyncrecognize",
1373            http_method: hyper::Method::POST,
1374        });
1375
1376        for &field in ["alt"].iter() {
1377            if self._additional_params.contains_key(field) {
1378                dlg.finished(false);
1379                return Err(common::Error::FieldClash(field));
1380            }
1381        }
1382
1383        let mut params = Params::with_capacity(3 + self._additional_params.len());
1384
1385        params.extend(self._additional_params.iter());
1386
1387        params.push("alt", "json");
1388        let mut url = self.hub._base_url.clone() + "v1beta1/speech:asyncrecognize";
1389        if self._scopes.is_empty() {
1390            self._scopes
1391                .insert(Scope::CloudPlatform.as_ref().to_string());
1392        }
1393
1394        let url = params.parse_with_url(&url);
1395
1396        let mut json_mime_type = mime::APPLICATION_JSON;
1397        let mut request_value_reader = {
1398            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1399            common::remove_json_null_values(&mut value);
1400            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1401            serde_json::to_writer(&mut dst, &value).unwrap();
1402            dst
1403        };
1404        let request_size = request_value_reader
1405            .seek(std::io::SeekFrom::End(0))
1406            .unwrap();
1407        request_value_reader
1408            .seek(std::io::SeekFrom::Start(0))
1409            .unwrap();
1410
1411        loop {
1412            let token = match self
1413                .hub
1414                .auth
1415                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1416                .await
1417            {
1418                Ok(token) => token,
1419                Err(e) => match dlg.token(e) {
1420                    Ok(token) => token,
1421                    Err(e) => {
1422                        dlg.finished(false);
1423                        return Err(common::Error::MissingToken(e));
1424                    }
1425                },
1426            };
1427            request_value_reader
1428                .seek(std::io::SeekFrom::Start(0))
1429                .unwrap();
1430            let mut req_result = {
1431                let client = &self.hub.client;
1432                dlg.pre_request();
1433                let mut req_builder = hyper::Request::builder()
1434                    .method(hyper::Method::POST)
1435                    .uri(url.as_str())
1436                    .header(USER_AGENT, self.hub._user_agent.clone());
1437
1438                if let Some(token) = token.as_ref() {
1439                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1440                }
1441
1442                let request = req_builder
1443                    .header(CONTENT_TYPE, json_mime_type.to_string())
1444                    .header(CONTENT_LENGTH, request_size as u64)
1445                    .body(common::to_body(
1446                        request_value_reader.get_ref().clone().into(),
1447                    ));
1448
1449                client.request(request.unwrap()).await
1450            };
1451
1452            match req_result {
1453                Err(err) => {
1454                    if let common::Retry::After(d) = dlg.http_error(&err) {
1455                        sleep(d).await;
1456                        continue;
1457                    }
1458                    dlg.finished(false);
1459                    return Err(common::Error::HttpError(err));
1460                }
1461                Ok(res) => {
1462                    let (mut parts, body) = res.into_parts();
1463                    let mut body = common::Body::new(body);
1464                    if !parts.status.is_success() {
1465                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1466                        let error = serde_json::from_str(&common::to_string(&bytes));
1467                        let response = common::to_response(parts, bytes.into());
1468
1469                        if let common::Retry::After(d) =
1470                            dlg.http_failure(&response, error.as_ref().ok())
1471                        {
1472                            sleep(d).await;
1473                            continue;
1474                        }
1475
1476                        dlg.finished(false);
1477
1478                        return Err(match error {
1479                            Ok(value) => common::Error::BadRequest(value),
1480                            _ => common::Error::Failure(response),
1481                        });
1482                    }
1483                    let response = {
1484                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1485                        let encoded = common::to_string(&bytes);
1486                        match serde_json::from_str(&encoded) {
1487                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1488                            Err(error) => {
1489                                dlg.response_json_decode_error(&encoded, &error);
1490                                return Err(common::Error::JsonDecodeError(
1491                                    encoded.to_string(),
1492                                    error,
1493                                ));
1494                            }
1495                        }
1496                    };
1497
1498                    dlg.finished(true);
1499                    return Ok(response);
1500                }
1501            }
1502        }
1503    }
1504
1505    ///
1506    /// Sets the *request* property to the given value.
1507    ///
1508    /// Even though the property as already been set when instantiating this call,
1509    /// we provide this method for API completeness.
1510    pub fn request(mut self, new_value: AsyncRecognizeRequest) -> SpeechAsyncrecognizeCall<'a, C> {
1511        self._request = new_value;
1512        self
1513    }
1514    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1515    /// while executing the actual API request.
1516    ///
1517    /// ````text
1518    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1519    /// ````
1520    ///
1521    /// Sets the *delegate* property to the given value.
1522    pub fn delegate(
1523        mut self,
1524        new_value: &'a mut dyn common::Delegate,
1525    ) -> SpeechAsyncrecognizeCall<'a, C> {
1526        self._delegate = Some(new_value);
1527        self
1528    }
1529
1530    /// Set any additional parameter of the query string used in the request.
1531    /// It should be used to set parameters which are not yet available through their own
1532    /// setters.
1533    ///
1534    /// Please note that this method must not be used to set any of the known parameters
1535    /// which have their own setter method. If done anyway, the request will fail.
1536    ///
1537    /// # Additional Parameters
1538    ///
1539    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1540    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1541    /// * *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.
1542    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1543    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1544    /// * *callback* (query-string) - JSONP
1545    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1546    /// * *$.xgafv* (query-string) - V1 error format.
1547    /// * *alt* (query-string) - Data format for response.
1548    /// * *access_token* (query-string) - OAuth access token.
1549    /// * *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.
1550    pub fn param<T>(mut self, name: T, value: T) -> SpeechAsyncrecognizeCall<'a, C>
1551    where
1552        T: AsRef<str>,
1553    {
1554        self._additional_params
1555            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1556        self
1557    }
1558
1559    /// Identifies the authorization scope for the method you are building.
1560    ///
1561    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1562    /// [`Scope::CloudPlatform`].
1563    ///
1564    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1565    /// tokens for more than one scope.
1566    ///
1567    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1568    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1569    /// sufficient, a read-write scope will do as well.
1570    pub fn add_scope<St>(mut self, scope: St) -> SpeechAsyncrecognizeCall<'a, C>
1571    where
1572        St: AsRef<str>,
1573    {
1574        self._scopes.insert(String::from(scope.as_ref()));
1575        self
1576    }
1577    /// Identifies the authorization scope(s) for the method you are building.
1578    ///
1579    /// See [`Self::add_scope()`] for details.
1580    pub fn add_scopes<I, St>(mut self, scopes: I) -> SpeechAsyncrecognizeCall<'a, C>
1581    where
1582        I: IntoIterator<Item = St>,
1583        St: AsRef<str>,
1584    {
1585        self._scopes
1586            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1587        self
1588    }
1589
1590    /// Removes all scopes, and no default scope will be used either.
1591    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1592    /// for details).
1593    pub fn clear_scopes(mut self) -> SpeechAsyncrecognizeCall<'a, C> {
1594        self._scopes.clear();
1595        self
1596    }
1597}
1598
1599/// Performs synchronous speech recognition: receive results after all audio
1600/// has been sent and processed.
1601///
1602/// A builder for the *syncrecognize* method supported by a *speech* resource.
1603/// It is not used directly, but through a [`SpeechMethods`] instance.
1604///
1605/// # Example
1606///
1607/// Instantiate a resource method builder
1608///
1609/// ```test_harness,no_run
1610/// # extern crate hyper;
1611/// # extern crate hyper_rustls;
1612/// # extern crate google_speech1_beta1 as speech1_beta1;
1613/// use speech1_beta1::api::SyncRecognizeRequest;
1614/// # async fn dox() {
1615/// # use speech1_beta1::{Speech, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1616///
1617/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1618/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1619/// #     secret,
1620/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1621/// # ).build().await.unwrap();
1622///
1623/// # let client = hyper_util::client::legacy::Client::builder(
1624/// #     hyper_util::rt::TokioExecutor::new()
1625/// # )
1626/// # .build(
1627/// #     hyper_rustls::HttpsConnectorBuilder::new()
1628/// #         .with_native_roots()
1629/// #         .unwrap()
1630/// #         .https_or_http()
1631/// #         .enable_http1()
1632/// #         .build()
1633/// # );
1634/// # let mut hub = Speech::new(client, auth);
1635/// // As the method needs a request, you would usually fill it with the desired information
1636/// // into the respective structure. Some of the parts shown here might not be applicable !
1637/// // Values shown here are possibly random and not representative !
1638/// let mut req = SyncRecognizeRequest::default();
1639///
1640/// // You can configure optional parameters by calling the respective setters at will, and
1641/// // execute the final call using `doit()`.
1642/// // Values shown here are possibly random and not representative !
1643/// let result = hub.speech().syncrecognize(req)
1644///              .doit().await;
1645/// # }
1646/// ```
1647pub struct SpeechSyncrecognizeCall<'a, C>
1648where
1649    C: 'a,
1650{
1651    hub: &'a Speech<C>,
1652    _request: SyncRecognizeRequest,
1653    _delegate: Option<&'a mut dyn common::Delegate>,
1654    _additional_params: HashMap<String, String>,
1655    _scopes: BTreeSet<String>,
1656}
1657
1658impl<'a, C> common::CallBuilder for SpeechSyncrecognizeCall<'a, C> {}
1659
1660impl<'a, C> SpeechSyncrecognizeCall<'a, C>
1661where
1662    C: common::Connector,
1663{
1664    /// Perform the operation you have build so far.
1665    pub async fn doit(mut self) -> common::Result<(common::Response, SyncRecognizeResponse)> {
1666        use std::borrow::Cow;
1667        use std::io::{Read, Seek};
1668
1669        use common::{url::Params, ToParts};
1670        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1671
1672        let mut dd = common::DefaultDelegate;
1673        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1674        dlg.begin(common::MethodInfo {
1675            id: "speech.speech.syncrecognize",
1676            http_method: hyper::Method::POST,
1677        });
1678
1679        for &field in ["alt"].iter() {
1680            if self._additional_params.contains_key(field) {
1681                dlg.finished(false);
1682                return Err(common::Error::FieldClash(field));
1683            }
1684        }
1685
1686        let mut params = Params::with_capacity(3 + self._additional_params.len());
1687
1688        params.extend(self._additional_params.iter());
1689
1690        params.push("alt", "json");
1691        let mut url = self.hub._base_url.clone() + "v1beta1/speech:syncrecognize";
1692        if self._scopes.is_empty() {
1693            self._scopes
1694                .insert(Scope::CloudPlatform.as_ref().to_string());
1695        }
1696
1697        let url = params.parse_with_url(&url);
1698
1699        let mut json_mime_type = mime::APPLICATION_JSON;
1700        let mut request_value_reader = {
1701            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1702            common::remove_json_null_values(&mut value);
1703            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1704            serde_json::to_writer(&mut dst, &value).unwrap();
1705            dst
1706        };
1707        let request_size = request_value_reader
1708            .seek(std::io::SeekFrom::End(0))
1709            .unwrap();
1710        request_value_reader
1711            .seek(std::io::SeekFrom::Start(0))
1712            .unwrap();
1713
1714        loop {
1715            let token = match self
1716                .hub
1717                .auth
1718                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1719                .await
1720            {
1721                Ok(token) => token,
1722                Err(e) => match dlg.token(e) {
1723                    Ok(token) => token,
1724                    Err(e) => {
1725                        dlg.finished(false);
1726                        return Err(common::Error::MissingToken(e));
1727                    }
1728                },
1729            };
1730            request_value_reader
1731                .seek(std::io::SeekFrom::Start(0))
1732                .unwrap();
1733            let mut req_result = {
1734                let client = &self.hub.client;
1735                dlg.pre_request();
1736                let mut req_builder = hyper::Request::builder()
1737                    .method(hyper::Method::POST)
1738                    .uri(url.as_str())
1739                    .header(USER_AGENT, self.hub._user_agent.clone());
1740
1741                if let Some(token) = token.as_ref() {
1742                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1743                }
1744
1745                let request = req_builder
1746                    .header(CONTENT_TYPE, json_mime_type.to_string())
1747                    .header(CONTENT_LENGTH, request_size as u64)
1748                    .body(common::to_body(
1749                        request_value_reader.get_ref().clone().into(),
1750                    ));
1751
1752                client.request(request.unwrap()).await
1753            };
1754
1755            match req_result {
1756                Err(err) => {
1757                    if let common::Retry::After(d) = dlg.http_error(&err) {
1758                        sleep(d).await;
1759                        continue;
1760                    }
1761                    dlg.finished(false);
1762                    return Err(common::Error::HttpError(err));
1763                }
1764                Ok(res) => {
1765                    let (mut parts, body) = res.into_parts();
1766                    let mut body = common::Body::new(body);
1767                    if !parts.status.is_success() {
1768                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1769                        let error = serde_json::from_str(&common::to_string(&bytes));
1770                        let response = common::to_response(parts, bytes.into());
1771
1772                        if let common::Retry::After(d) =
1773                            dlg.http_failure(&response, error.as_ref().ok())
1774                        {
1775                            sleep(d).await;
1776                            continue;
1777                        }
1778
1779                        dlg.finished(false);
1780
1781                        return Err(match error {
1782                            Ok(value) => common::Error::BadRequest(value),
1783                            _ => common::Error::Failure(response),
1784                        });
1785                    }
1786                    let response = {
1787                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1788                        let encoded = common::to_string(&bytes);
1789                        match serde_json::from_str(&encoded) {
1790                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1791                            Err(error) => {
1792                                dlg.response_json_decode_error(&encoded, &error);
1793                                return Err(common::Error::JsonDecodeError(
1794                                    encoded.to_string(),
1795                                    error,
1796                                ));
1797                            }
1798                        }
1799                    };
1800
1801                    dlg.finished(true);
1802                    return Ok(response);
1803                }
1804            }
1805        }
1806    }
1807
1808    ///
1809    /// Sets the *request* property to the given value.
1810    ///
1811    /// Even though the property as already been set when instantiating this call,
1812    /// we provide this method for API completeness.
1813    pub fn request(mut self, new_value: SyncRecognizeRequest) -> SpeechSyncrecognizeCall<'a, C> {
1814        self._request = new_value;
1815        self
1816    }
1817    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1818    /// while executing the actual API request.
1819    ///
1820    /// ````text
1821    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1822    /// ````
1823    ///
1824    /// Sets the *delegate* property to the given value.
1825    pub fn delegate(
1826        mut self,
1827        new_value: &'a mut dyn common::Delegate,
1828    ) -> SpeechSyncrecognizeCall<'a, C> {
1829        self._delegate = Some(new_value);
1830        self
1831    }
1832
1833    /// Set any additional parameter of the query string used in the request.
1834    /// It should be used to set parameters which are not yet available through their own
1835    /// setters.
1836    ///
1837    /// Please note that this method must not be used to set any of the known parameters
1838    /// which have their own setter method. If done anyway, the request will fail.
1839    ///
1840    /// # Additional Parameters
1841    ///
1842    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1843    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1844    /// * *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.
1845    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1846    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1847    /// * *callback* (query-string) - JSONP
1848    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1849    /// * *$.xgafv* (query-string) - V1 error format.
1850    /// * *alt* (query-string) - Data format for response.
1851    /// * *access_token* (query-string) - OAuth access token.
1852    /// * *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.
1853    pub fn param<T>(mut self, name: T, value: T) -> SpeechSyncrecognizeCall<'a, C>
1854    where
1855        T: AsRef<str>,
1856    {
1857        self._additional_params
1858            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1859        self
1860    }
1861
1862    /// Identifies the authorization scope for the method you are building.
1863    ///
1864    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1865    /// [`Scope::CloudPlatform`].
1866    ///
1867    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1868    /// tokens for more than one scope.
1869    ///
1870    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1871    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1872    /// sufficient, a read-write scope will do as well.
1873    pub fn add_scope<St>(mut self, scope: St) -> SpeechSyncrecognizeCall<'a, C>
1874    where
1875        St: AsRef<str>,
1876    {
1877        self._scopes.insert(String::from(scope.as_ref()));
1878        self
1879    }
1880    /// Identifies the authorization scope(s) for the method you are building.
1881    ///
1882    /// See [`Self::add_scope()`] for details.
1883    pub fn add_scopes<I, St>(mut self, scopes: I) -> SpeechSyncrecognizeCall<'a, C>
1884    where
1885        I: IntoIterator<Item = St>,
1886        St: AsRef<str>,
1887    {
1888        self._scopes
1889            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1890        self
1891    }
1892
1893    /// Removes all scopes, and no default scope will be used either.
1894    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1895    /// for details).
1896    pub fn clear_scopes(mut self) -> SpeechSyncrecognizeCall<'a, C> {
1897        self._scopes.clear();
1898        self
1899    }
1900}