google_videointelligence1_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 CloudVideoIntelligence 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_videointelligence1_beta1 as videointelligence1_beta1;
49/// use videointelligence1_beta1::api::GoogleCloudVideointelligenceV1beta1_AnnotateVideoRequest;
50/// use videointelligence1_beta1::{Result, Error};
51/// # async fn dox() {
52/// use videointelligence1_beta1::{CloudVideoIntelligence, 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 = CloudVideoIntelligence::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 = GoogleCloudVideointelligenceV1beta1_AnnotateVideoRequest::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.videos().annotate(req)
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 CloudVideoIntelligence<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 CloudVideoIntelligence<C> {}
130
131impl<'a, C> CloudVideoIntelligence<C> {
132 pub fn new<A: 'static + common::GetToken>(
133 client: common::Client<C>,
134 auth: A,
135 ) -> CloudVideoIntelligence<C> {
136 CloudVideoIntelligence {
137 client,
138 auth: Box::new(auth),
139 _user_agent: "google-api-rust-client/7.0.0".to_string(),
140 _base_url: "https://videointelligence.googleapis.com/".to_string(),
141 _root_url: "https://videointelligence.googleapis.com/".to_string(),
142 }
143 }
144
145 pub fn videos(&'a self) -> VideoMethods<'a, C> {
146 VideoMethods { hub: self }
147 }
148
149 /// Set the user-agent header field to use in all requests to the server.
150 /// It defaults to `google-api-rust-client/7.0.0`.
151 ///
152 /// Returns the previously set user-agent.
153 pub fn user_agent(&mut self, agent_name: String) -> String {
154 std::mem::replace(&mut self._user_agent, agent_name)
155 }
156
157 /// Set the base url to use in all requests to the server.
158 /// It defaults to `https://videointelligence.googleapis.com/`.
159 ///
160 /// Returns the previously set base url.
161 pub fn base_url(&mut self, new_base_url: String) -> String {
162 std::mem::replace(&mut self._base_url, new_base_url)
163 }
164
165 /// Set the root url to use in all requests to the server.
166 /// It defaults to `https://videointelligence.googleapis.com/`.
167 ///
168 /// Returns the previously set root url.
169 pub fn root_url(&mut self, new_root_url: String) -> String {
170 std::mem::replace(&mut self._root_url, new_root_url)
171 }
172}
173
174// ############
175// SCHEMAS ###
176// ##########
177/// This resource represents a long-running operation that is the result of a
178/// network API call.
179///
180/// # Activities
181///
182/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
183/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
184///
185/// * [annotate videos](VideoAnnotateCall) (response)
186#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
187#[serde_with::serde_as]
188#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
189pub struct GoogleLongrunning_Operation {
190 /// If the value is `false`, it means the operation is still in progress.
191 /// If `true`, the operation is completed, and either `error` or `response` is
192 /// available.
193 pub done: Option<bool>,
194 /// The normal response of the operation in case of success. If the original
195 /// method returns no data on success, such as `Delete`, the response is
196 /// `google.protobuf.Empty`. If the original method is standard
197 /// `Get`/`Create`/`Update`, the response should be the resource. For other
198 /// methods, the response should have the type `XxxResponse`, where `Xxx`
199 /// is the original method name. For example, if the original method name
200 /// is `TakeSnapshot()`, the inferred response type is
201 /// `TakeSnapshotResponse`.
202 pub response: Option<HashMap<String, serde_json::Value>>,
203 /// The server-assigned name, which is only unique within the same service that
204 /// originally returns it. If you use the default HTTP mapping, the
205 /// `name` should have the format of `operations/some/unique/name`.
206 pub name: Option<String>,
207 /// The error result of the operation in case of failure or cancellation.
208 pub error: Option<GoogleRpc_Status>,
209 /// Service-specific metadata associated with the operation. It typically
210 /// contains progress information and common metadata such as create time.
211 /// Some services might not provide such metadata. Any method that returns a
212 /// long-running operation should document the metadata type, if any.
213 pub metadata: Option<HashMap<String, serde_json::Value>>,
214}
215
216impl common::ResponseResult for GoogleLongrunning_Operation {}
217
218/// Video annotation request.
219///
220/// # Activities
221///
222/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
223/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
224///
225/// * [annotate videos](VideoAnnotateCall) (request)
226#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
227#[serde_with::serde_as]
228#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
229pub struct GoogleCloudVideointelligenceV1beta1_AnnotateVideoRequest {
230 /// Optional location where the output (in JSON format) should be stored.
231 /// Currently, only [Google Cloud Storage](https://cloud.google.com/storage/)
232 /// URIs are supported, which must be specified in the following format:
233 /// `gs://bucket-id/object-id` (other URI formats return
234 /// google.rpc.Code.INVALID_ARGUMENT). For more information, see
235 /// [Request URIs](https://cloud.google.com/storage/docs/reference-uris).
236 #[serde(rename = "outputUri")]
237 pub output_uri: Option<String>,
238 /// Requested video annotation features.
239 pub features: Option<Vec<String>>,
240 /// Additional video context and/or feature-specific parameters.
241 #[serde(rename = "videoContext")]
242 pub video_context: Option<GoogleCloudVideointelligenceV1beta1_VideoContext>,
243 /// Optional cloud region where annotation should take place. Supported cloud
244 /// regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region
245 /// is specified, a region will be determined based on video file location.
246 #[serde(rename = "locationId")]
247 pub location_id: Option<String>,
248 /// Input video location. Currently, only
249 /// [Google Cloud Storage](https://cloud.google.com/storage/) URIs are
250 /// supported, which must be specified in the following format:
251 /// `gs://bucket-id/object-id` (other URI formats return
252 /// google.rpc.Code.INVALID_ARGUMENT). For more information, see
253 /// [Request URIs](https://cloud.google.com/storage/docs/reference-uris).
254 /// A video URI may include wildcards in `object-id`, and thus identify
255 /// multiple videos. Supported wildcards: ‘\*’ to match 0 or more characters;
256 /// ‘?’ to match 1 character. If unset, the input video should be embedded
257 /// in the request as `input_content`. If set, `input_content` should be unset.
258 #[serde(rename = "inputUri")]
259 pub input_uri: Option<String>,
260 /// The video data bytes. Encoding: base64. If unset, the input video(s)
261 /// should be specified via `input_uri`. If set, `input_uri` should be unset.
262 #[serde(rename = "inputContent")]
263 pub input_content: Option<String>,
264}
265
266impl common::RequestValue for GoogleCloudVideointelligenceV1beta1_AnnotateVideoRequest {}
267
268/// Video segment.
269///
270/// This type is not used in any activity, and only used as *part* of another schema.
271///
272#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
273#[serde_with::serde_as]
274#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
275pub struct GoogleCloudVideointelligenceV1beta1_VideoSegment {
276 /// End offset in microseconds (inclusive). Unset means 0.
277 #[serde(rename = "endTimeOffset")]
278 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
279 pub end_time_offset: Option<i64>,
280 /// Start offset in microseconds (inclusive). Unset means 0.
281 #[serde(rename = "startTimeOffset")]
282 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
283 pub start_time_offset: Option<i64>,
284}
285
286impl common::Part for GoogleCloudVideointelligenceV1beta1_VideoSegment {}
287
288/// Video context and/or feature-specific parameters.
289///
290/// This type is not used in any activity, and only used as *part* of another schema.
291///
292#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
293#[serde_with::serde_as]
294#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
295pub struct GoogleCloudVideointelligenceV1beta1_VideoContext {
296 /// Model to use for safe search detection.
297 /// Supported values: "latest" and "stable" (the default).
298 #[serde(rename = "safeSearchDetectionModel")]
299 pub safe_search_detection_model: Option<String>,
300 /// Video segments to annotate. The segments may overlap and are not required
301 /// to be contiguous or span the whole video. If unspecified, each video
302 /// is treated as a single segment.
303 pub segments: Option<Vec<GoogleCloudVideointelligenceV1beta1_VideoSegment>>,
304 /// Model to use for label detection.
305 /// Supported values: "latest" and "stable" (the default).
306 #[serde(rename = "labelDetectionModel")]
307 pub label_detection_model: Option<String>,
308 /// Model to use for shot change detection.
309 /// Supported values: "latest" and "stable" (the default).
310 #[serde(rename = "shotChangeDetectionModel")]
311 pub shot_change_detection_model: Option<String>,
312 /// If label detection has been requested, what labels should be detected
313 /// in addition to video-level labels or segment-level labels. If unspecified,
314 /// defaults to `SHOT_MODE`.
315 #[serde(rename = "labelDetectionMode")]
316 pub label_detection_mode: Option<String>,
317 /// Whether the video has been shot from a stationary (i.e. non-moving) camera.
318 /// When set to true, might improve detection accuracy for moving objects.
319 #[serde(rename = "stationaryCamera")]
320 pub stationary_camera: Option<bool>,
321}
322
323impl common::Part for GoogleCloudVideointelligenceV1beta1_VideoContext {}
324
325/// The `Status` type defines a logical error model that is suitable for different
326/// programming environments, including REST APIs and RPC APIs. It is used by
327/// [gRPC](https://github.com/grpc). The error model is designed to be:
328///
329/// * Simple to use and understand for most users
330/// * Flexible enough to meet unexpected needs
331///
332/// # Overview
333///
334/// The `Status` message contains three pieces of data: error code, error message,
335/// and error details. The error code should be an enum value of
336/// google.rpc.Code, but it may accept additional error codes if needed. The
337/// error message should be a developer-facing English message that helps
338/// developers *understand* and *resolve* the error. If a localized user-facing
339/// error message is needed, put the localized message in the error details or
340/// localize it in the client. The optional error details may contain arbitrary
341/// information about the error. There is a predefined set of error detail types
342/// in the package `google.rpc` that can be used for common error conditions.
343///
344/// # Language mapping
345///
346/// The `Status` message is the logical representation of the error model, but it
347/// is not necessarily the actual wire format. When the `Status` message is
348/// exposed in different client libraries and different wire protocols, it can be
349/// mapped differently. For example, it will likely be mapped to some exceptions
350/// in Java, but more likely mapped to some error codes in C.
351///
352/// # Other uses
353///
354/// The error model and the `Status` message can be used in a variety of
355/// environments, either with or without APIs, to provide a
356/// consistent developer experience across different environments.
357///
358/// Example uses of this error model include:
359///
360/// * Partial errors. If a service needs to return partial errors to the client,
361/// it may embed the `Status` in the normal response to indicate the partial
362/// errors.
363///
364/// * Workflow errors. A typical workflow has multiple steps. Each step may
365/// have a `Status` message for error reporting.
366///
367/// * Batch operations. If a client uses batch request and batch response, the
368/// `Status` message should be used directly inside batch response, one for
369/// each error sub-response.
370///
371/// * Asynchronous operations. If an API call embeds asynchronous operation
372/// results in its response, the status of those operations should be
373/// represented directly using the `Status` message.
374///
375/// * Logging. If some API errors are stored in logs, the message `Status` could
376/// be used directly after any stripping needed for security/privacy reasons.
377///
378/// This type is not used in any activity, and only used as *part* of another schema.
379#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
380#[serde_with::serde_as]
381#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
382pub struct GoogleRpc_Status {
383 /// A list of messages that carry the error details. There is a common set of
384 /// message types for APIs to use.
385 pub details: Option<Vec<HashMap<String, serde_json::Value>>>,
386 /// The status code, which should be an enum value of google.rpc.Code.
387 pub code: Option<i32>,
388 /// A developer-facing error message, which should be in English. Any
389 /// user-facing error message should be localized and sent in the
390 /// google.rpc.Status.details field, or localized by the client.
391 pub message: Option<String>,
392}
393
394impl common::Part for GoogleRpc_Status {}
395
396// ###################
397// MethodBuilders ###
398// #################
399
400/// A builder providing access to all methods supported on *video* resources.
401/// It is not used directly, but through the [`CloudVideoIntelligence`] hub.
402///
403/// # Example
404///
405/// Instantiate a resource builder
406///
407/// ```test_harness,no_run
408/// extern crate hyper;
409/// extern crate hyper_rustls;
410/// extern crate google_videointelligence1_beta1 as videointelligence1_beta1;
411///
412/// # async fn dox() {
413/// use videointelligence1_beta1::{CloudVideoIntelligence, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
414///
415/// let secret: yup_oauth2::ApplicationSecret = Default::default();
416/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
417/// .with_native_roots()
418/// .unwrap()
419/// .https_only()
420/// .enable_http2()
421/// .build();
422///
423/// let executor = hyper_util::rt::TokioExecutor::new();
424/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
425/// secret,
426/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
427/// yup_oauth2::client::CustomHyperClientBuilder::from(
428/// hyper_util::client::legacy::Client::builder(executor).build(connector),
429/// ),
430/// ).build().await.unwrap();
431///
432/// let client = hyper_util::client::legacy::Client::builder(
433/// hyper_util::rt::TokioExecutor::new()
434/// )
435/// .build(
436/// hyper_rustls::HttpsConnectorBuilder::new()
437/// .with_native_roots()
438/// .unwrap()
439/// .https_or_http()
440/// .enable_http2()
441/// .build()
442/// );
443/// let mut hub = CloudVideoIntelligence::new(client, auth);
444/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
445/// // like `annotate(...)`
446/// // to build up your call.
447/// let rb = hub.videos();
448/// # }
449/// ```
450pub struct VideoMethods<'a, C>
451where
452 C: 'a,
453{
454 hub: &'a CloudVideoIntelligence<C>,
455}
456
457impl<'a, C> common::MethodsBuilder for VideoMethods<'a, C> {}
458
459impl<'a, C> VideoMethods<'a, C> {
460 /// Create a builder to help you perform the following task:
461 ///
462 /// Performs asynchronous video annotation. Progress and results can be
463 /// retrieved through the `google.longrunning.Operations` interface.
464 /// `Operation.metadata` contains `AnnotateVideoProgress` (progress).
465 /// `Operation.response` contains `AnnotateVideoResponse` (results).
466 ///
467 /// # Arguments
468 ///
469 /// * `request` - No description provided.
470 pub fn annotate(
471 &self,
472 request: GoogleCloudVideointelligenceV1beta1_AnnotateVideoRequest,
473 ) -> VideoAnnotateCall<'a, C> {
474 VideoAnnotateCall {
475 hub: self.hub,
476 _request: request,
477 _delegate: Default::default(),
478 _additional_params: Default::default(),
479 _scopes: Default::default(),
480 }
481 }
482}
483
484// ###################
485// CallBuilders ###
486// #################
487
488/// Performs asynchronous video annotation. Progress and results can be
489/// retrieved through the `google.longrunning.Operations` interface.
490/// `Operation.metadata` contains `AnnotateVideoProgress` (progress).
491/// `Operation.response` contains `AnnotateVideoResponse` (results).
492///
493/// A builder for the *annotate* method supported by a *video* resource.
494/// It is not used directly, but through a [`VideoMethods`] instance.
495///
496/// # Example
497///
498/// Instantiate a resource method builder
499///
500/// ```test_harness,no_run
501/// # extern crate hyper;
502/// # extern crate hyper_rustls;
503/// # extern crate google_videointelligence1_beta1 as videointelligence1_beta1;
504/// use videointelligence1_beta1::api::GoogleCloudVideointelligenceV1beta1_AnnotateVideoRequest;
505/// # async fn dox() {
506/// # use videointelligence1_beta1::{CloudVideoIntelligence, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
507///
508/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
509/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
510/// # .with_native_roots()
511/// # .unwrap()
512/// # .https_only()
513/// # .enable_http2()
514/// # .build();
515///
516/// # let executor = hyper_util::rt::TokioExecutor::new();
517/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
518/// # secret,
519/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
520/// # yup_oauth2::client::CustomHyperClientBuilder::from(
521/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
522/// # ),
523/// # ).build().await.unwrap();
524///
525/// # let client = hyper_util::client::legacy::Client::builder(
526/// # hyper_util::rt::TokioExecutor::new()
527/// # )
528/// # .build(
529/// # hyper_rustls::HttpsConnectorBuilder::new()
530/// # .with_native_roots()
531/// # .unwrap()
532/// # .https_or_http()
533/// # .enable_http2()
534/// # .build()
535/// # );
536/// # let mut hub = CloudVideoIntelligence::new(client, auth);
537/// // As the method needs a request, you would usually fill it with the desired information
538/// // into the respective structure. Some of the parts shown here might not be applicable !
539/// // Values shown here are possibly random and not representative !
540/// let mut req = GoogleCloudVideointelligenceV1beta1_AnnotateVideoRequest::default();
541///
542/// // You can configure optional parameters by calling the respective setters at will, and
543/// // execute the final call using `doit()`.
544/// // Values shown here are possibly random and not representative !
545/// let result = hub.videos().annotate(req)
546/// .doit().await;
547/// # }
548/// ```
549pub struct VideoAnnotateCall<'a, C>
550where
551 C: 'a,
552{
553 hub: &'a CloudVideoIntelligence<C>,
554 _request: GoogleCloudVideointelligenceV1beta1_AnnotateVideoRequest,
555 _delegate: Option<&'a mut dyn common::Delegate>,
556 _additional_params: HashMap<String, String>,
557 _scopes: BTreeSet<String>,
558}
559
560impl<'a, C> common::CallBuilder for VideoAnnotateCall<'a, C> {}
561
562impl<'a, C> VideoAnnotateCall<'a, C>
563where
564 C: common::Connector,
565{
566 /// Perform the operation you have build so far.
567 pub async fn doit(mut self) -> common::Result<(common::Response, GoogleLongrunning_Operation)> {
568 use std::borrow::Cow;
569 use std::io::{Read, Seek};
570
571 use common::{url::Params, ToParts};
572 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
573
574 let mut dd = common::DefaultDelegate;
575 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
576 dlg.begin(common::MethodInfo {
577 id: "videointelligence.videos.annotate",
578 http_method: hyper::Method::POST,
579 });
580
581 for &field in ["alt"].iter() {
582 if self._additional_params.contains_key(field) {
583 dlg.finished(false);
584 return Err(common::Error::FieldClash(field));
585 }
586 }
587
588 let mut params = Params::with_capacity(3 + self._additional_params.len());
589
590 params.extend(self._additional_params.iter());
591
592 params.push("alt", "json");
593 let mut url = self.hub._base_url.clone() + "v1beta1/videos:annotate";
594 if self._scopes.is_empty() {
595 self._scopes
596 .insert(Scope::CloudPlatform.as_ref().to_string());
597 }
598
599 let url = params.parse_with_url(&url);
600
601 let mut json_mime_type = mime::APPLICATION_JSON;
602 let mut request_value_reader = {
603 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
604 common::remove_json_null_values(&mut value);
605 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
606 serde_json::to_writer(&mut dst, &value).unwrap();
607 dst
608 };
609 let request_size = request_value_reader
610 .seek(std::io::SeekFrom::End(0))
611 .unwrap();
612 request_value_reader
613 .seek(std::io::SeekFrom::Start(0))
614 .unwrap();
615
616 loop {
617 let token = match self
618 .hub
619 .auth
620 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
621 .await
622 {
623 Ok(token) => token,
624 Err(e) => match dlg.token(e) {
625 Ok(token) => token,
626 Err(e) => {
627 dlg.finished(false);
628 return Err(common::Error::MissingToken(e));
629 }
630 },
631 };
632 request_value_reader
633 .seek(std::io::SeekFrom::Start(0))
634 .unwrap();
635 let mut req_result = {
636 let client = &self.hub.client;
637 dlg.pre_request();
638 let mut req_builder = hyper::Request::builder()
639 .method(hyper::Method::POST)
640 .uri(url.as_str())
641 .header(USER_AGENT, self.hub._user_agent.clone());
642
643 if let Some(token) = token.as_ref() {
644 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
645 }
646
647 let request = req_builder
648 .header(CONTENT_TYPE, json_mime_type.to_string())
649 .header(CONTENT_LENGTH, request_size as u64)
650 .body(common::to_body(
651 request_value_reader.get_ref().clone().into(),
652 ));
653
654 client.request(request.unwrap()).await
655 };
656
657 match req_result {
658 Err(err) => {
659 if let common::Retry::After(d) = dlg.http_error(&err) {
660 sleep(d).await;
661 continue;
662 }
663 dlg.finished(false);
664 return Err(common::Error::HttpError(err));
665 }
666 Ok(res) => {
667 let (mut parts, body) = res.into_parts();
668 let mut body = common::Body::new(body);
669 if !parts.status.is_success() {
670 let bytes = common::to_bytes(body).await.unwrap_or_default();
671 let error = serde_json::from_str(&common::to_string(&bytes));
672 let response = common::to_response(parts, bytes.into());
673
674 if let common::Retry::After(d) =
675 dlg.http_failure(&response, error.as_ref().ok())
676 {
677 sleep(d).await;
678 continue;
679 }
680
681 dlg.finished(false);
682
683 return Err(match error {
684 Ok(value) => common::Error::BadRequest(value),
685 _ => common::Error::Failure(response),
686 });
687 }
688 let response = {
689 let bytes = common::to_bytes(body).await.unwrap_or_default();
690 let encoded = common::to_string(&bytes);
691 match serde_json::from_str(&encoded) {
692 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
693 Err(error) => {
694 dlg.response_json_decode_error(&encoded, &error);
695 return Err(common::Error::JsonDecodeError(
696 encoded.to_string(),
697 error,
698 ));
699 }
700 }
701 };
702
703 dlg.finished(true);
704 return Ok(response);
705 }
706 }
707 }
708 }
709
710 ///
711 /// Sets the *request* property to the given value.
712 ///
713 /// Even though the property as already been set when instantiating this call,
714 /// we provide this method for API completeness.
715 pub fn request(
716 mut self,
717 new_value: GoogleCloudVideointelligenceV1beta1_AnnotateVideoRequest,
718 ) -> VideoAnnotateCall<'a, C> {
719 self._request = new_value;
720 self
721 }
722 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
723 /// while executing the actual API request.
724 ///
725 /// ````text
726 /// It should be used to handle progress information, and to implement a certain level of resilience.
727 /// ````
728 ///
729 /// Sets the *delegate* property to the given value.
730 pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> VideoAnnotateCall<'a, C> {
731 self._delegate = Some(new_value);
732 self
733 }
734
735 /// Set any additional parameter of the query string used in the request.
736 /// It should be used to set parameters which are not yet available through their own
737 /// setters.
738 ///
739 /// Please note that this method must not be used to set any of the known parameters
740 /// which have their own setter method. If done anyway, the request will fail.
741 ///
742 /// # Additional Parameters
743 ///
744 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
745 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
746 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
747 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
748 /// * *callback* (query-string) - JSONP
749 /// * *$.xgafv* (query-string) - V1 error format.
750 /// * *alt* (query-string) - Data format for response.
751 /// * *access_token* (query-string) - OAuth access token.
752 /// * *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.
753 /// * *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.
754 /// * *pp* (query-boolean) - Pretty-print response.
755 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
756 /// * *bearer_token* (query-string) - OAuth bearer token.
757 pub fn param<T>(mut self, name: T, value: T) -> VideoAnnotateCall<'a, C>
758 where
759 T: AsRef<str>,
760 {
761 self._additional_params
762 .insert(name.as_ref().to_string(), value.as_ref().to_string());
763 self
764 }
765
766 /// Identifies the authorization scope for the method you are building.
767 ///
768 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
769 /// [`Scope::CloudPlatform`].
770 ///
771 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
772 /// tokens for more than one scope.
773 ///
774 /// Usually there is more than one suitable scope to authorize an operation, some of which may
775 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
776 /// sufficient, a read-write scope will do as well.
777 pub fn add_scope<St>(mut self, scope: St) -> VideoAnnotateCall<'a, C>
778 where
779 St: AsRef<str>,
780 {
781 self._scopes.insert(String::from(scope.as_ref()));
782 self
783 }
784 /// Identifies the authorization scope(s) for the method you are building.
785 ///
786 /// See [`Self::add_scope()`] for details.
787 pub fn add_scopes<I, St>(mut self, scopes: I) -> VideoAnnotateCall<'a, C>
788 where
789 I: IntoIterator<Item = St>,
790 St: AsRef<str>,
791 {
792 self._scopes
793 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
794 self
795 }
796
797 /// Removes all scopes, and no default scope will be used either.
798 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
799 /// for details).
800 pub fn clear_scopes(mut self) -> VideoAnnotateCall<'a, C> {
801 self._scopes.clear();
802 self
803 }
804}