google_language1/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 /// Apply machine learning models to reveal the structure and meaning of text
17 CloudLanguage,
18
19 /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
20 CloudPlatform,
21}
22
23impl AsRef<str> for Scope {
24 fn as_ref(&self) -> &str {
25 match *self {
26 Scope::CloudLanguage => "https://www.googleapis.com/auth/cloud-language",
27 Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
28 }
29 }
30}
31
32#[allow(clippy::derivable_impls)]
33impl Default for Scope {
34 fn default() -> Scope {
35 Scope::CloudLanguage
36 }
37}
38
39// ########
40// HUB ###
41// ######
42
43/// Central instance to access all CloudNaturalLanguage related resource activities
44///
45/// # Examples
46///
47/// Instantiate a new hub
48///
49/// ```test_harness,no_run
50/// extern crate hyper;
51/// extern crate hyper_rustls;
52/// extern crate google_language1 as language1;
53/// use language1::api::AnalyzeEntitiesRequest;
54/// use language1::{Result, Error};
55/// # async fn dox() {
56/// use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
57///
58/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
59/// // `client_secret`, among other things.
60/// let secret: yup_oauth2::ApplicationSecret = Default::default();
61/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
62/// // unless you replace `None` with the desired Flow.
63/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
64/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
65/// // retrieve them from storage.
66/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
67/// .with_native_roots()
68/// .unwrap()
69/// .https_only()
70/// .enable_http2()
71/// .build();
72///
73/// let executor = hyper_util::rt::TokioExecutor::new();
74/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
75/// secret,
76/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
77/// yup_oauth2::client::CustomHyperClientBuilder::from(
78/// hyper_util::client::legacy::Client::builder(executor).build(connector),
79/// ),
80/// ).build().await.unwrap();
81///
82/// let client = hyper_util::client::legacy::Client::builder(
83/// hyper_util::rt::TokioExecutor::new()
84/// )
85/// .build(
86/// hyper_rustls::HttpsConnectorBuilder::new()
87/// .with_native_roots()
88/// .unwrap()
89/// .https_or_http()
90/// .enable_http2()
91/// .build()
92/// );
93/// let mut hub = CloudNaturalLanguage::new(client, auth);
94/// // As the method needs a request, you would usually fill it with the desired information
95/// // into the respective structure. Some of the parts shown here might not be applicable !
96/// // Values shown here are possibly random and not representative !
97/// let mut req = AnalyzeEntitiesRequest::default();
98///
99/// // You can configure optional parameters by calling the respective setters at will, and
100/// // execute the final call using `doit()`.
101/// // Values shown here are possibly random and not representative !
102/// let result = hub.documents().analyze_entities(req)
103/// .doit().await;
104///
105/// match result {
106/// Err(e) => match e {
107/// // The Error enum provides details about what exactly happened.
108/// // You can also just use its `Debug`, `Display` or `Error` traits
109/// Error::HttpError(_)
110/// |Error::Io(_)
111/// |Error::MissingAPIKey
112/// |Error::MissingToken(_)
113/// |Error::Cancelled
114/// |Error::UploadSizeLimitExceeded(_, _)
115/// |Error::Failure(_)
116/// |Error::BadRequest(_)
117/// |Error::FieldClash(_)
118/// |Error::JsonDecodeError(_, _) => println!("{}", e),
119/// },
120/// Ok(res) => println!("Success: {:?}", res),
121/// }
122/// # }
123/// ```
124#[derive(Clone)]
125pub struct CloudNaturalLanguage<C> {
126 pub client: common::Client<C>,
127 pub auth: Box<dyn common::GetToken>,
128 _user_agent: String,
129 _base_url: String,
130 _root_url: String,
131}
132
133impl<C> common::Hub for CloudNaturalLanguage<C> {}
134
135impl<'a, C> CloudNaturalLanguage<C> {
136 pub fn new<A: 'static + common::GetToken>(
137 client: common::Client<C>,
138 auth: A,
139 ) -> CloudNaturalLanguage<C> {
140 CloudNaturalLanguage {
141 client,
142 auth: Box::new(auth),
143 _user_agent: "google-api-rust-client/7.0.0".to_string(),
144 _base_url: "https://language.googleapis.com/".to_string(),
145 _root_url: "https://language.googleapis.com/".to_string(),
146 }
147 }
148
149 pub fn documents(&'a self) -> DocumentMethods<'a, C> {
150 DocumentMethods { hub: self }
151 }
152
153 /// Set the user-agent header field to use in all requests to the server.
154 /// It defaults to `google-api-rust-client/7.0.0`.
155 ///
156 /// Returns the previously set user-agent.
157 pub fn user_agent(&mut self, agent_name: String) -> String {
158 std::mem::replace(&mut self._user_agent, agent_name)
159 }
160
161 /// Set the base url to use in all requests to the server.
162 /// It defaults to `https://language.googleapis.com/`.
163 ///
164 /// Returns the previously set base url.
165 pub fn base_url(&mut self, new_base_url: String) -> String {
166 std::mem::replace(&mut self._base_url, new_base_url)
167 }
168
169 /// Set the root url to use in all requests to the server.
170 /// It defaults to `https://language.googleapis.com/`.
171 ///
172 /// Returns the previously set root url.
173 pub fn root_url(&mut self, new_root_url: String) -> String {
174 std::mem::replace(&mut self._root_url, new_root_url)
175 }
176}
177
178// ############
179// SCHEMAS ###
180// ##########
181/// The entity analysis request message.
182///
183/// # Activities
184///
185/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
186/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
187///
188/// * [analyze entities documents](DocumentAnalyzeEntityCall) (request)
189#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
190#[serde_with::serde_as]
191#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
192pub struct AnalyzeEntitiesRequest {
193 /// Required. Input document.
194 pub document: Option<Document>,
195 /// The encoding type used by the API to calculate offsets.
196 #[serde(rename = "encodingType")]
197 pub encoding_type: Option<String>,
198}
199
200impl common::RequestValue for AnalyzeEntitiesRequest {}
201
202/// The entity analysis response message.
203///
204/// # Activities
205///
206/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
207/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
208///
209/// * [analyze entities documents](DocumentAnalyzeEntityCall) (response)
210#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
211#[serde_with::serde_as]
212#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
213pub struct AnalyzeEntitiesResponse {
214 /// The recognized entities in the input document.
215 pub entities: Option<Vec<Entity>>,
216 /// The language of the text, which will be the same as the language specified in the request or, if not specified, the automatically-detected language. See Document.language field for more details.
217 pub language: Option<String>,
218}
219
220impl common::ResponseResult for AnalyzeEntitiesResponse {}
221
222/// The entity-level sentiment analysis request message.
223///
224/// # Activities
225///
226/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
227/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
228///
229/// * [analyze entity sentiment documents](DocumentAnalyzeEntitySentimentCall) (request)
230#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
231#[serde_with::serde_as]
232#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
233pub struct AnalyzeEntitySentimentRequest {
234 /// Required. Input document.
235 pub document: Option<Document>,
236 /// The encoding type used by the API to calculate offsets.
237 #[serde(rename = "encodingType")]
238 pub encoding_type: Option<String>,
239}
240
241impl common::RequestValue for AnalyzeEntitySentimentRequest {}
242
243/// The entity-level sentiment analysis response message.
244///
245/// # Activities
246///
247/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
248/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
249///
250/// * [analyze entity sentiment documents](DocumentAnalyzeEntitySentimentCall) (response)
251#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
252#[serde_with::serde_as]
253#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
254pub struct AnalyzeEntitySentimentResponse {
255 /// The recognized entities in the input document with associated sentiments.
256 pub entities: Option<Vec<Entity>>,
257 /// The language of the text, which will be the same as the language specified in the request or, if not specified, the automatically-detected language. See Document.language field for more details.
258 pub language: Option<String>,
259}
260
261impl common::ResponseResult for AnalyzeEntitySentimentResponse {}
262
263/// The sentiment analysis request message.
264///
265/// # Activities
266///
267/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
268/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
269///
270/// * [analyze sentiment documents](DocumentAnalyzeSentimentCall) (request)
271#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
272#[serde_with::serde_as]
273#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
274pub struct AnalyzeSentimentRequest {
275 /// Required. Input document.
276 pub document: Option<Document>,
277 /// The encoding type used by the API to calculate sentence offsets.
278 #[serde(rename = "encodingType")]
279 pub encoding_type: Option<String>,
280}
281
282impl common::RequestValue for AnalyzeSentimentRequest {}
283
284/// The sentiment analysis response message.
285///
286/// # Activities
287///
288/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
289/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
290///
291/// * [analyze sentiment documents](DocumentAnalyzeSentimentCall) (response)
292#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
293#[serde_with::serde_as]
294#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
295pub struct AnalyzeSentimentResponse {
296 /// The overall sentiment of the input document.
297 #[serde(rename = "documentSentiment")]
298 pub document_sentiment: Option<Sentiment>,
299 /// The language of the text, which will be the same as the language specified in the request or, if not specified, the automatically-detected language. See Document.language field for more details.
300 pub language: Option<String>,
301 /// The sentiment for all the sentences in the document.
302 pub sentences: Option<Vec<Sentence>>,
303}
304
305impl common::ResponseResult for AnalyzeSentimentResponse {}
306
307/// The syntax analysis request message.
308///
309/// # Activities
310///
311/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
312/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
313///
314/// * [analyze syntax documents](DocumentAnalyzeSyntaxCall) (request)
315#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
316#[serde_with::serde_as]
317#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
318pub struct AnalyzeSyntaxRequest {
319 /// Required. Input document.
320 pub document: Option<Document>,
321 /// The encoding type used by the API to calculate offsets.
322 #[serde(rename = "encodingType")]
323 pub encoding_type: Option<String>,
324}
325
326impl common::RequestValue for AnalyzeSyntaxRequest {}
327
328/// The syntax analysis response message.
329///
330/// # Activities
331///
332/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
333/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
334///
335/// * [analyze syntax documents](DocumentAnalyzeSyntaxCall) (response)
336#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
337#[serde_with::serde_as]
338#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
339pub struct AnalyzeSyntaxResponse {
340 /// The language of the text, which will be the same as the language specified in the request or, if not specified, the automatically-detected language. See Document.language field for more details.
341 pub language: Option<String>,
342 /// Sentences in the input document.
343 pub sentences: Option<Vec<Sentence>>,
344 /// Tokens, along with their syntactic information, in the input document.
345 pub tokens: Option<Vec<Token>>,
346}
347
348impl common::ResponseResult for AnalyzeSyntaxResponse {}
349
350/// The request message for the text annotation API, which can perform multiple analysis types (sentiment, entities, and syntax) in one call.
351///
352/// # Activities
353///
354/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
355/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
356///
357/// * [annotate text documents](DocumentAnnotateTextCall) (request)
358#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
359#[serde_with::serde_as]
360#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
361pub struct AnnotateTextRequest {
362 /// Required. Input document.
363 pub document: Option<Document>,
364 /// The encoding type used by the API to calculate offsets.
365 #[serde(rename = "encodingType")]
366 pub encoding_type: Option<String>,
367 /// Required. The enabled features.
368 pub features: Option<AnnotateTextRequestFeatures>,
369}
370
371impl common::RequestValue for AnnotateTextRequest {}
372
373/// All available features for sentiment, syntax, and semantic analysis. Setting each one to true will enable that specific analysis for the input.
374///
375/// This type is not used in any activity, and only used as *part* of another schema.
376///
377#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
378#[serde_with::serde_as]
379#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
380pub struct AnnotateTextRequestFeatures {
381 /// Optional. The model options to use for classification. Defaults to v1 options if not specified. Only used if `classify_text` is set to true.
382 #[serde(rename = "classificationModelOptions")]
383 pub classification_model_options: Option<ClassificationModelOptions>,
384 /// Classify the full document into categories.
385 #[serde(rename = "classifyText")]
386 pub classify_text: Option<bool>,
387 /// Extract document-level sentiment.
388 #[serde(rename = "extractDocumentSentiment")]
389 pub extract_document_sentiment: Option<bool>,
390 /// Extract entities.
391 #[serde(rename = "extractEntities")]
392 pub extract_entities: Option<bool>,
393 /// Extract entities and their associated sentiment.
394 #[serde(rename = "extractEntitySentiment")]
395 pub extract_entity_sentiment: Option<bool>,
396 /// Extract syntax information.
397 #[serde(rename = "extractSyntax")]
398 pub extract_syntax: Option<bool>,
399 /// Moderate the document for harmful and sensitive categories.
400 #[serde(rename = "moderateText")]
401 pub moderate_text: Option<bool>,
402}
403
404impl common::Part for AnnotateTextRequestFeatures {}
405
406/// The text annotations response message.
407///
408/// # Activities
409///
410/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
411/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
412///
413/// * [annotate text documents](DocumentAnnotateTextCall) (response)
414#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
415#[serde_with::serde_as]
416#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
417pub struct AnnotateTextResponse {
418 /// Categories identified in the input document.
419 pub categories: Option<Vec<ClassificationCategory>>,
420 /// The overall sentiment for the document. Populated if the user enables AnnotateTextRequest.Features.extract_document_sentiment.
421 #[serde(rename = "documentSentiment")]
422 pub document_sentiment: Option<Sentiment>,
423 /// Entities, along with their semantic information, in the input document. Populated if the user enables AnnotateTextRequest.Features.extract_entities.
424 pub entities: Option<Vec<Entity>>,
425 /// The language of the text, which will be the same as the language specified in the request or, if not specified, the automatically-detected language. See Document.language field for more details.
426 pub language: Option<String>,
427 /// Harmful and sensitive categories identified in the input document.
428 #[serde(rename = "moderationCategories")]
429 pub moderation_categories: Option<Vec<ClassificationCategory>>,
430 /// Sentences in the input document. Populated if the user enables AnnotateTextRequest.Features.extract_syntax.
431 pub sentences: Option<Vec<Sentence>>,
432 /// Tokens, along with their syntactic information, in the input document. Populated if the user enables AnnotateTextRequest.Features.extract_syntax.
433 pub tokens: Option<Vec<Token>>,
434}
435
436impl common::ResponseResult for AnnotateTextResponse {}
437
438/// Represents a category returned from the text classifier.
439///
440/// This type is not used in any activity, and only used as *part* of another schema.
441///
442#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
443#[serde_with::serde_as]
444#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
445pub struct ClassificationCategory {
446 /// The classifier's confidence of the category. Number represents how certain the classifier is that this category represents the given text.
447 pub confidence: Option<f32>,
448 /// The name of the category representing the document.
449 pub name: Option<String>,
450}
451
452impl common::Part for ClassificationCategory {}
453
454/// Model options available for classification requests.
455///
456/// This type is not used in any activity, and only used as *part* of another schema.
457///
458#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
459#[serde_with::serde_as]
460#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
461pub struct ClassificationModelOptions {
462 /// Setting this field will use the V1 model and V1 content categories version. The V1 model is a legacy model; support for this will be discontinued in the future.
463 #[serde(rename = "v1Model")]
464 pub v1_model: Option<ClassificationModelOptionsV1Model>,
465 /// Setting this field will use the V2 model with the appropriate content categories version. The V2 model is a better performing model.
466 #[serde(rename = "v2Model")]
467 pub v2_model: Option<ClassificationModelOptionsV2Model>,
468}
469
470impl common::Part for ClassificationModelOptions {}
471
472/// Options for the V1 model.
473///
474/// This type is not used in any activity, and only used as *part* of another schema.
475///
476#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
477#[serde_with::serde_as]
478#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
479pub struct ClassificationModelOptionsV1Model {
480 _never_set: Option<bool>,
481}
482
483impl common::Part for ClassificationModelOptionsV1Model {}
484
485/// Options for the V2 model.
486///
487/// This type is not used in any activity, and only used as *part* of another schema.
488///
489#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
490#[serde_with::serde_as]
491#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
492pub struct ClassificationModelOptionsV2Model {
493 /// The content categories used for classification.
494 #[serde(rename = "contentCategoriesVersion")]
495 pub content_categories_version: Option<String>,
496}
497
498impl common::Part for ClassificationModelOptionsV2Model {}
499
500/// The document classification request message.
501///
502/// # Activities
503///
504/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
505/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
506///
507/// * [classify text documents](DocumentClassifyTextCall) (request)
508#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
509#[serde_with::serde_as]
510#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
511pub struct ClassifyTextRequest {
512 /// Optional. Model options to use for classification. Defaults to v1 options if not specified.
513 #[serde(rename = "classificationModelOptions")]
514 pub classification_model_options: Option<ClassificationModelOptions>,
515 /// Required. Input document.
516 pub document: Option<Document>,
517}
518
519impl common::RequestValue for ClassifyTextRequest {}
520
521/// The document classification response message.
522///
523/// # Activities
524///
525/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
526/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
527///
528/// * [classify text documents](DocumentClassifyTextCall) (response)
529#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
530#[serde_with::serde_as]
531#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
532pub struct ClassifyTextResponse {
533 /// Categories representing the input document.
534 pub categories: Option<Vec<ClassificationCategory>>,
535}
536
537impl common::ResponseResult for ClassifyTextResponse {}
538
539/// Represents dependency parse tree information for a token. (For more information on dependency labels, see http://www.aclweb.org/anthology/P13-2017
540///
541/// This type is not used in any activity, and only used as *part* of another schema.
542///
543#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
544#[serde_with::serde_as]
545#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
546pub struct DependencyEdge {
547 /// Represents the head of this token in the dependency tree. This is the index of the token which has an arc going to this token. The index is the position of the token in the array of tokens returned by the API method. If this token is a root token, then the `head_token_index` is its own index.
548 #[serde(rename = "headTokenIndex")]
549 pub head_token_index: Option<i32>,
550 /// The parse label for the token.
551 pub label: Option<String>,
552}
553
554impl common::Part for DependencyEdge {}
555
556/// Represents the input to API methods.
557///
558/// # Activities
559///
560/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
561/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
562///
563/// * [analyze entities documents](DocumentAnalyzeEntityCall) (none)
564/// * [analyze entity sentiment documents](DocumentAnalyzeEntitySentimentCall) (none)
565/// * [analyze sentiment documents](DocumentAnalyzeSentimentCall) (none)
566/// * [analyze syntax documents](DocumentAnalyzeSyntaxCall) (none)
567/// * [annotate text documents](DocumentAnnotateTextCall) (none)
568/// * [classify text documents](DocumentClassifyTextCall) (none)
569/// * [moderate text documents](DocumentModerateTextCall) (none)
570#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
571#[serde_with::serde_as]
572#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
573pub struct Document {
574 /// The content of the input in string format. Cloud audit logging exempt since it is based on user data.
575 pub content: Option<String>,
576 /// The Google Cloud Storage URI where the file content is located. This URI must be of the form: gs://bucket_name/object_name. For more details, see https://cloud.google.com/storage/docs/reference-uris. NOTE: Cloud Storage object versioning is not supported.
577 #[serde(rename = "gcsContentUri")]
578 pub gcs_content_uri: Option<String>,
579 /// The language of the document (if not specified, the language is automatically detected). Both ISO and BCP-47 language codes are accepted. [Language Support](https://cloud.google.com/natural-language/docs/languages) lists currently supported languages for each API method. If the language (either specified by the caller or automatically detected) is not supported by the called API method, an `INVALID_ARGUMENT` error is returned.
580 pub language: Option<String>,
581 /// Required. If the type is not set or is `TYPE_UNSPECIFIED`, returns an `INVALID_ARGUMENT` error.
582 #[serde(rename = "type")]
583 pub type_: Option<String>,
584}
585
586impl common::Resource for Document {}
587
588/// Represents a phrase in the text that is a known entity, such as a person, an organization, or location. The API associates information, such as salience and mentions, with entities.
589///
590/// This type is not used in any activity, and only used as *part* of another schema.
591///
592#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
593#[serde_with::serde_as]
594#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
595pub struct Entity {
596 /// The mentions of this entity in the input document. The API currently supports proper noun mentions.
597 pub mentions: Option<Vec<EntityMention>>,
598 /// Metadata associated with the entity. For most entity types, the metadata is a Wikipedia URL (`wikipedia_url`) and Knowledge Graph MID (`mid`), if they are available. For the metadata associated with other entity types, see the Type table below.
599 pub metadata: Option<HashMap<String, String>>,
600 /// The representative name for the entity.
601 pub name: Option<String>,
602 /// The salience score associated with the entity in the [0, 1.0] range. The salience score for an entity provides information about the importance or centrality of that entity to the entire document text. Scores closer to 0 are less salient, while scores closer to 1.0 are highly salient.
603 pub salience: Option<f32>,
604 /// For calls to AnalyzeEntitySentiment or if AnnotateTextRequest.Features.extract_entity_sentiment is set to true, this field will contain the aggregate sentiment expressed for this entity in the provided document.
605 pub sentiment: Option<Sentiment>,
606 /// The entity type.
607 #[serde(rename = "type")]
608 pub type_: Option<String>,
609}
610
611impl common::Part for Entity {}
612
613/// Represents a mention for an entity in the text. Currently, proper noun mentions are supported.
614///
615/// This type is not used in any activity, and only used as *part* of another schema.
616///
617#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
618#[serde_with::serde_as]
619#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
620pub struct EntityMention {
621 /// For calls to AnalyzeEntitySentiment or if AnnotateTextRequest.Features.extract_entity_sentiment is set to true, this field will contain the sentiment expressed for this mention of the entity in the provided document.
622 pub sentiment: Option<Sentiment>,
623 /// The mention text.
624 pub text: Option<TextSpan>,
625 /// The type of the entity mention.
626 #[serde(rename = "type")]
627 pub type_: Option<String>,
628}
629
630impl common::Part for EntityMention {}
631
632/// The document moderation request message.
633///
634/// # Activities
635///
636/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
637/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
638///
639/// * [moderate text documents](DocumentModerateTextCall) (request)
640#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
641#[serde_with::serde_as]
642#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
643pub struct ModerateTextRequest {
644 /// Required. Input document.
645 pub document: Option<Document>,
646}
647
648impl common::RequestValue for ModerateTextRequest {}
649
650/// The document moderation response message.
651///
652/// # Activities
653///
654/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
655/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
656///
657/// * [moderate text documents](DocumentModerateTextCall) (response)
658#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
659#[serde_with::serde_as]
660#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
661pub struct ModerateTextResponse {
662 /// Harmful and sensitive categories representing the input document.
663 #[serde(rename = "moderationCategories")]
664 pub moderation_categories: Option<Vec<ClassificationCategory>>,
665}
666
667impl common::ResponseResult for ModerateTextResponse {}
668
669/// Represents part of speech information for a token. Parts of speech are as defined in http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf
670///
671/// This type is not used in any activity, and only used as *part* of another schema.
672///
673#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
674#[serde_with::serde_as]
675#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
676pub struct PartOfSpeech {
677 /// The grammatical aspect.
678 pub aspect: Option<String>,
679 /// The grammatical case.
680 pub case: Option<String>,
681 /// The grammatical form.
682 pub form: Option<String>,
683 /// The grammatical gender.
684 pub gender: Option<String>,
685 /// The grammatical mood.
686 pub mood: Option<String>,
687 /// The grammatical number.
688 pub number: Option<String>,
689 /// The grammatical person.
690 pub person: Option<String>,
691 /// The grammatical properness.
692 pub proper: Option<String>,
693 /// The grammatical reciprocity.
694 pub reciprocity: Option<String>,
695 /// The part of speech tag.
696 pub tag: Option<String>,
697 /// The grammatical tense.
698 pub tense: Option<String>,
699 /// The grammatical voice.
700 pub voice: Option<String>,
701}
702
703impl common::Part for PartOfSpeech {}
704
705/// Represents a sentence in the input document.
706///
707/// This type is not used in any activity, and only used as *part* of another schema.
708///
709#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
710#[serde_with::serde_as]
711#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
712pub struct Sentence {
713 /// For calls to AnalyzeSentiment or if AnnotateTextRequest.Features.extract_document_sentiment is set to true, this field will contain the sentiment for the sentence.
714 pub sentiment: Option<Sentiment>,
715 /// The sentence text.
716 pub text: Option<TextSpan>,
717}
718
719impl common::Part for Sentence {}
720
721/// Represents the feeling associated with the entire text or entities in the text.
722///
723/// This type is not used in any activity, and only used as *part* of another schema.
724///
725#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
726#[serde_with::serde_as]
727#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
728pub struct Sentiment {
729 /// A non-negative number in the [0, +inf) range, which represents the absolute magnitude of sentiment regardless of score (positive or negative).
730 pub magnitude: Option<f32>,
731 /// Sentiment score between -1.0 (negative sentiment) and 1.0 (positive sentiment).
732 pub score: Option<f32>,
733}
734
735impl common::Part for Sentiment {}
736
737/// Represents a text span in the input document.
738///
739/// This type is not used in any activity, and only used as *part* of another schema.
740///
741#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
742#[serde_with::serde_as]
743#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
744pub struct TextSpan {
745 /// The API calculates the beginning offset of the content in the original document according to the EncodingType specified in the API request.
746 #[serde(rename = "beginOffset")]
747 pub begin_offset: Option<i32>,
748 /// The content of the text span, which is a substring of the document.
749 pub content: Option<String>,
750}
751
752impl common::Part for TextSpan {}
753
754/// Represents the smallest syntactic building block of the text.
755///
756/// This type is not used in any activity, and only used as *part* of another schema.
757///
758#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
759#[serde_with::serde_as]
760#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
761pub struct Token {
762 /// Dependency tree parse for this token.
763 #[serde(rename = "dependencyEdge")]
764 pub dependency_edge: Option<DependencyEdge>,
765 /// [Lemma](https://en.wikipedia.org/wiki/Lemma_%28morphology%29) of the token.
766 pub lemma: Option<String>,
767 /// Parts of speech tag for this token.
768 #[serde(rename = "partOfSpeech")]
769 pub part_of_speech: Option<PartOfSpeech>,
770 /// The token text.
771 pub text: Option<TextSpan>,
772}
773
774impl common::Part for Token {}
775
776// ###################
777// MethodBuilders ###
778// #################
779
780/// A builder providing access to all methods supported on *document* resources.
781/// It is not used directly, but through the [`CloudNaturalLanguage`] hub.
782///
783/// # Example
784///
785/// Instantiate a resource builder
786///
787/// ```test_harness,no_run
788/// extern crate hyper;
789/// extern crate hyper_rustls;
790/// extern crate google_language1 as language1;
791///
792/// # async fn dox() {
793/// use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
794///
795/// let secret: yup_oauth2::ApplicationSecret = Default::default();
796/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
797/// .with_native_roots()
798/// .unwrap()
799/// .https_only()
800/// .enable_http2()
801/// .build();
802///
803/// let executor = hyper_util::rt::TokioExecutor::new();
804/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
805/// secret,
806/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
807/// yup_oauth2::client::CustomHyperClientBuilder::from(
808/// hyper_util::client::legacy::Client::builder(executor).build(connector),
809/// ),
810/// ).build().await.unwrap();
811///
812/// let client = hyper_util::client::legacy::Client::builder(
813/// hyper_util::rt::TokioExecutor::new()
814/// )
815/// .build(
816/// hyper_rustls::HttpsConnectorBuilder::new()
817/// .with_native_roots()
818/// .unwrap()
819/// .https_or_http()
820/// .enable_http2()
821/// .build()
822/// );
823/// let mut hub = CloudNaturalLanguage::new(client, auth);
824/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
825/// // like `analyze_entities(...)`, `analyze_entity_sentiment(...)`, `analyze_sentiment(...)`, `analyze_syntax(...)`, `annotate_text(...)`, `classify_text(...)` and `moderate_text(...)`
826/// // to build up your call.
827/// let rb = hub.documents();
828/// # }
829/// ```
830pub struct DocumentMethods<'a, C>
831where
832 C: 'a,
833{
834 hub: &'a CloudNaturalLanguage<C>,
835}
836
837impl<'a, C> common::MethodsBuilder for DocumentMethods<'a, C> {}
838
839impl<'a, C> DocumentMethods<'a, C> {
840 /// Create a builder to help you perform the following task:
841 ///
842 /// Finds named entities (currently proper names and common nouns) in the text along with entity types, salience, mentions for each entity, and other properties.
843 ///
844 /// # Arguments
845 ///
846 /// * `request` - No description provided.
847 pub fn analyze_entities(
848 &self,
849 request: AnalyzeEntitiesRequest,
850 ) -> DocumentAnalyzeEntityCall<'a, C> {
851 DocumentAnalyzeEntityCall {
852 hub: self.hub,
853 _request: request,
854 _delegate: Default::default(),
855 _additional_params: Default::default(),
856 _scopes: Default::default(),
857 }
858 }
859
860 /// Create a builder to help you perform the following task:
861 ///
862 /// Finds entities, similar to AnalyzeEntities in the text and analyzes sentiment associated with each entity and its mentions.
863 ///
864 /// # Arguments
865 ///
866 /// * `request` - No description provided.
867 pub fn analyze_entity_sentiment(
868 &self,
869 request: AnalyzeEntitySentimentRequest,
870 ) -> DocumentAnalyzeEntitySentimentCall<'a, C> {
871 DocumentAnalyzeEntitySentimentCall {
872 hub: self.hub,
873 _request: request,
874 _delegate: Default::default(),
875 _additional_params: Default::default(),
876 _scopes: Default::default(),
877 }
878 }
879
880 /// Create a builder to help you perform the following task:
881 ///
882 /// Analyzes the sentiment of the provided text.
883 ///
884 /// # Arguments
885 ///
886 /// * `request` - No description provided.
887 pub fn analyze_sentiment(
888 &self,
889 request: AnalyzeSentimentRequest,
890 ) -> DocumentAnalyzeSentimentCall<'a, C> {
891 DocumentAnalyzeSentimentCall {
892 hub: self.hub,
893 _request: request,
894 _delegate: Default::default(),
895 _additional_params: Default::default(),
896 _scopes: Default::default(),
897 }
898 }
899
900 /// Create a builder to help you perform the following task:
901 ///
902 /// Analyzes the syntax of the text and provides sentence boundaries and tokenization along with part of speech tags, dependency trees, and other properties.
903 ///
904 /// # Arguments
905 ///
906 /// * `request` - No description provided.
907 pub fn analyze_syntax(
908 &self,
909 request: AnalyzeSyntaxRequest,
910 ) -> DocumentAnalyzeSyntaxCall<'a, C> {
911 DocumentAnalyzeSyntaxCall {
912 hub: self.hub,
913 _request: request,
914 _delegate: Default::default(),
915 _additional_params: Default::default(),
916 _scopes: Default::default(),
917 }
918 }
919
920 /// Create a builder to help you perform the following task:
921 ///
922 /// A convenience method that provides all the features that analyzeSentiment, analyzeEntities, and analyzeSyntax provide in one call.
923 ///
924 /// # Arguments
925 ///
926 /// * `request` - No description provided.
927 pub fn annotate_text(&self, request: AnnotateTextRequest) -> DocumentAnnotateTextCall<'a, C> {
928 DocumentAnnotateTextCall {
929 hub: self.hub,
930 _request: request,
931 _delegate: Default::default(),
932 _additional_params: Default::default(),
933 _scopes: Default::default(),
934 }
935 }
936
937 /// Create a builder to help you perform the following task:
938 ///
939 /// Classifies a document into categories.
940 ///
941 /// # Arguments
942 ///
943 /// * `request` - No description provided.
944 pub fn classify_text(&self, request: ClassifyTextRequest) -> DocumentClassifyTextCall<'a, C> {
945 DocumentClassifyTextCall {
946 hub: self.hub,
947 _request: request,
948 _delegate: Default::default(),
949 _additional_params: Default::default(),
950 _scopes: Default::default(),
951 }
952 }
953
954 /// Create a builder to help you perform the following task:
955 ///
956 /// Moderates a document for harmful and sensitive categories.
957 ///
958 /// # Arguments
959 ///
960 /// * `request` - No description provided.
961 pub fn moderate_text(&self, request: ModerateTextRequest) -> DocumentModerateTextCall<'a, C> {
962 DocumentModerateTextCall {
963 hub: self.hub,
964 _request: request,
965 _delegate: Default::default(),
966 _additional_params: Default::default(),
967 _scopes: Default::default(),
968 }
969 }
970}
971
972// ###################
973// CallBuilders ###
974// #################
975
976/// Finds named entities (currently proper names and common nouns) in the text along with entity types, salience, mentions for each entity, and other properties.
977///
978/// A builder for the *analyzeEntities* method supported by a *document* resource.
979/// It is not used directly, but through a [`DocumentMethods`] instance.
980///
981/// # Example
982///
983/// Instantiate a resource method builder
984///
985/// ```test_harness,no_run
986/// # extern crate hyper;
987/// # extern crate hyper_rustls;
988/// # extern crate google_language1 as language1;
989/// use language1::api::AnalyzeEntitiesRequest;
990/// # async fn dox() {
991/// # use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
992///
993/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
994/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
995/// # .with_native_roots()
996/// # .unwrap()
997/// # .https_only()
998/// # .enable_http2()
999/// # .build();
1000///
1001/// # let executor = hyper_util::rt::TokioExecutor::new();
1002/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1003/// # secret,
1004/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1005/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1006/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1007/// # ),
1008/// # ).build().await.unwrap();
1009///
1010/// # let client = hyper_util::client::legacy::Client::builder(
1011/// # hyper_util::rt::TokioExecutor::new()
1012/// # )
1013/// # .build(
1014/// # hyper_rustls::HttpsConnectorBuilder::new()
1015/// # .with_native_roots()
1016/// # .unwrap()
1017/// # .https_or_http()
1018/// # .enable_http2()
1019/// # .build()
1020/// # );
1021/// # let mut hub = CloudNaturalLanguage::new(client, auth);
1022/// // As the method needs a request, you would usually fill it with the desired information
1023/// // into the respective structure. Some of the parts shown here might not be applicable !
1024/// // Values shown here are possibly random and not representative !
1025/// let mut req = AnalyzeEntitiesRequest::default();
1026///
1027/// // You can configure optional parameters by calling the respective setters at will, and
1028/// // execute the final call using `doit()`.
1029/// // Values shown here are possibly random and not representative !
1030/// let result = hub.documents().analyze_entities(req)
1031/// .doit().await;
1032/// # }
1033/// ```
1034pub struct DocumentAnalyzeEntityCall<'a, C>
1035where
1036 C: 'a,
1037{
1038 hub: &'a CloudNaturalLanguage<C>,
1039 _request: AnalyzeEntitiesRequest,
1040 _delegate: Option<&'a mut dyn common::Delegate>,
1041 _additional_params: HashMap<String, String>,
1042 _scopes: BTreeSet<String>,
1043}
1044
1045impl<'a, C> common::CallBuilder for DocumentAnalyzeEntityCall<'a, C> {}
1046
1047impl<'a, C> DocumentAnalyzeEntityCall<'a, C>
1048where
1049 C: common::Connector,
1050{
1051 /// Perform the operation you have build so far.
1052 pub async fn doit(mut self) -> common::Result<(common::Response, AnalyzeEntitiesResponse)> {
1053 use std::borrow::Cow;
1054 use std::io::{Read, Seek};
1055
1056 use common::{url::Params, ToParts};
1057 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1058
1059 let mut dd = common::DefaultDelegate;
1060 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1061 dlg.begin(common::MethodInfo {
1062 id: "language.documents.analyzeEntities",
1063 http_method: hyper::Method::POST,
1064 });
1065
1066 for &field in ["alt"].iter() {
1067 if self._additional_params.contains_key(field) {
1068 dlg.finished(false);
1069 return Err(common::Error::FieldClash(field));
1070 }
1071 }
1072
1073 let mut params = Params::with_capacity(3 + self._additional_params.len());
1074
1075 params.extend(self._additional_params.iter());
1076
1077 params.push("alt", "json");
1078 let mut url = self.hub._base_url.clone() + "v1/documents:analyzeEntities";
1079 if self._scopes.is_empty() {
1080 self._scopes
1081 .insert(Scope::CloudPlatform.as_ref().to_string());
1082 }
1083
1084 let url = params.parse_with_url(&url);
1085
1086 let mut json_mime_type = mime::APPLICATION_JSON;
1087 let mut request_value_reader = {
1088 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1089 common::remove_json_null_values(&mut value);
1090 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1091 serde_json::to_writer(&mut dst, &value).unwrap();
1092 dst
1093 };
1094 let request_size = request_value_reader
1095 .seek(std::io::SeekFrom::End(0))
1096 .unwrap();
1097 request_value_reader
1098 .seek(std::io::SeekFrom::Start(0))
1099 .unwrap();
1100
1101 loop {
1102 let token = match self
1103 .hub
1104 .auth
1105 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1106 .await
1107 {
1108 Ok(token) => token,
1109 Err(e) => match dlg.token(e) {
1110 Ok(token) => token,
1111 Err(e) => {
1112 dlg.finished(false);
1113 return Err(common::Error::MissingToken(e));
1114 }
1115 },
1116 };
1117 request_value_reader
1118 .seek(std::io::SeekFrom::Start(0))
1119 .unwrap();
1120 let mut req_result = {
1121 let client = &self.hub.client;
1122 dlg.pre_request();
1123 let mut req_builder = hyper::Request::builder()
1124 .method(hyper::Method::POST)
1125 .uri(url.as_str())
1126 .header(USER_AGENT, self.hub._user_agent.clone());
1127
1128 if let Some(token) = token.as_ref() {
1129 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1130 }
1131
1132 let request = req_builder
1133 .header(CONTENT_TYPE, json_mime_type.to_string())
1134 .header(CONTENT_LENGTH, request_size as u64)
1135 .body(common::to_body(
1136 request_value_reader.get_ref().clone().into(),
1137 ));
1138
1139 client.request(request.unwrap()).await
1140 };
1141
1142 match req_result {
1143 Err(err) => {
1144 if let common::Retry::After(d) = dlg.http_error(&err) {
1145 sleep(d).await;
1146 continue;
1147 }
1148 dlg.finished(false);
1149 return Err(common::Error::HttpError(err));
1150 }
1151 Ok(res) => {
1152 let (mut parts, body) = res.into_parts();
1153 let mut body = common::Body::new(body);
1154 if !parts.status.is_success() {
1155 let bytes = common::to_bytes(body).await.unwrap_or_default();
1156 let error = serde_json::from_str(&common::to_string(&bytes));
1157 let response = common::to_response(parts, bytes.into());
1158
1159 if let common::Retry::After(d) =
1160 dlg.http_failure(&response, error.as_ref().ok())
1161 {
1162 sleep(d).await;
1163 continue;
1164 }
1165
1166 dlg.finished(false);
1167
1168 return Err(match error {
1169 Ok(value) => common::Error::BadRequest(value),
1170 _ => common::Error::Failure(response),
1171 });
1172 }
1173 let response = {
1174 let bytes = common::to_bytes(body).await.unwrap_or_default();
1175 let encoded = common::to_string(&bytes);
1176 match serde_json::from_str(&encoded) {
1177 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1178 Err(error) => {
1179 dlg.response_json_decode_error(&encoded, &error);
1180 return Err(common::Error::JsonDecodeError(
1181 encoded.to_string(),
1182 error,
1183 ));
1184 }
1185 }
1186 };
1187
1188 dlg.finished(true);
1189 return Ok(response);
1190 }
1191 }
1192 }
1193 }
1194
1195 ///
1196 /// Sets the *request* property to the given value.
1197 ///
1198 /// Even though the property as already been set when instantiating this call,
1199 /// we provide this method for API completeness.
1200 pub fn request(
1201 mut self,
1202 new_value: AnalyzeEntitiesRequest,
1203 ) -> DocumentAnalyzeEntityCall<'a, C> {
1204 self._request = new_value;
1205 self
1206 }
1207 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1208 /// while executing the actual API request.
1209 ///
1210 /// ````text
1211 /// It should be used to handle progress information, and to implement a certain level of resilience.
1212 /// ````
1213 ///
1214 /// Sets the *delegate* property to the given value.
1215 pub fn delegate(
1216 mut self,
1217 new_value: &'a mut dyn common::Delegate,
1218 ) -> DocumentAnalyzeEntityCall<'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 /// * *$.xgafv* (query-string) - V1 error format.
1233 /// * *access_token* (query-string) - OAuth access token.
1234 /// * *alt* (query-string) - Data format for response.
1235 /// * *callback* (query-string) - JSONP
1236 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1237 /// * *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.
1238 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1239 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1240 /// * *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.
1241 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1242 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1243 pub fn param<T>(mut self, name: T, value: T) -> DocumentAnalyzeEntityCall<'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) -> DocumentAnalyzeEntityCall<'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) -> DocumentAnalyzeEntityCall<'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) -> DocumentAnalyzeEntityCall<'a, C> {
1287 self._scopes.clear();
1288 self
1289 }
1290}
1291
1292/// Finds entities, similar to AnalyzeEntities in the text and analyzes sentiment associated with each entity and its mentions.
1293///
1294/// A builder for the *analyzeEntitySentiment* method supported by a *document* resource.
1295/// It is not used directly, but through a [`DocumentMethods`] instance.
1296///
1297/// # Example
1298///
1299/// Instantiate a resource method builder
1300///
1301/// ```test_harness,no_run
1302/// # extern crate hyper;
1303/// # extern crate hyper_rustls;
1304/// # extern crate google_language1 as language1;
1305/// use language1::api::AnalyzeEntitySentimentRequest;
1306/// # async fn dox() {
1307/// # use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1308///
1309/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1310/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1311/// # .with_native_roots()
1312/// # .unwrap()
1313/// # .https_only()
1314/// # .enable_http2()
1315/// # .build();
1316///
1317/// # let executor = hyper_util::rt::TokioExecutor::new();
1318/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1319/// # secret,
1320/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1321/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1322/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1323/// # ),
1324/// # ).build().await.unwrap();
1325///
1326/// # let client = hyper_util::client::legacy::Client::builder(
1327/// # hyper_util::rt::TokioExecutor::new()
1328/// # )
1329/// # .build(
1330/// # hyper_rustls::HttpsConnectorBuilder::new()
1331/// # .with_native_roots()
1332/// # .unwrap()
1333/// # .https_or_http()
1334/// # .enable_http2()
1335/// # .build()
1336/// # );
1337/// # let mut hub = CloudNaturalLanguage::new(client, auth);
1338/// // As the method needs a request, you would usually fill it with the desired information
1339/// // into the respective structure. Some of the parts shown here might not be applicable !
1340/// // Values shown here are possibly random and not representative !
1341/// let mut req = AnalyzeEntitySentimentRequest::default();
1342///
1343/// // You can configure optional parameters by calling the respective setters at will, and
1344/// // execute the final call using `doit()`.
1345/// // Values shown here are possibly random and not representative !
1346/// let result = hub.documents().analyze_entity_sentiment(req)
1347/// .doit().await;
1348/// # }
1349/// ```
1350pub struct DocumentAnalyzeEntitySentimentCall<'a, C>
1351where
1352 C: 'a,
1353{
1354 hub: &'a CloudNaturalLanguage<C>,
1355 _request: AnalyzeEntitySentimentRequest,
1356 _delegate: Option<&'a mut dyn common::Delegate>,
1357 _additional_params: HashMap<String, String>,
1358 _scopes: BTreeSet<String>,
1359}
1360
1361impl<'a, C> common::CallBuilder for DocumentAnalyzeEntitySentimentCall<'a, C> {}
1362
1363impl<'a, C> DocumentAnalyzeEntitySentimentCall<'a, C>
1364where
1365 C: common::Connector,
1366{
1367 /// Perform the operation you have build so far.
1368 pub async fn doit(
1369 mut self,
1370 ) -> common::Result<(common::Response, AnalyzeEntitySentimentResponse)> {
1371 use std::borrow::Cow;
1372 use std::io::{Read, Seek};
1373
1374 use common::{url::Params, ToParts};
1375 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1376
1377 let mut dd = common::DefaultDelegate;
1378 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1379 dlg.begin(common::MethodInfo {
1380 id: "language.documents.analyzeEntitySentiment",
1381 http_method: hyper::Method::POST,
1382 });
1383
1384 for &field in ["alt"].iter() {
1385 if self._additional_params.contains_key(field) {
1386 dlg.finished(false);
1387 return Err(common::Error::FieldClash(field));
1388 }
1389 }
1390
1391 let mut params = Params::with_capacity(3 + self._additional_params.len());
1392
1393 params.extend(self._additional_params.iter());
1394
1395 params.push("alt", "json");
1396 let mut url = self.hub._base_url.clone() + "v1/documents:analyzeEntitySentiment";
1397 if self._scopes.is_empty() {
1398 self._scopes
1399 .insert(Scope::CloudPlatform.as_ref().to_string());
1400 }
1401
1402 let url = params.parse_with_url(&url);
1403
1404 let mut json_mime_type = mime::APPLICATION_JSON;
1405 let mut request_value_reader = {
1406 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1407 common::remove_json_null_values(&mut value);
1408 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1409 serde_json::to_writer(&mut dst, &value).unwrap();
1410 dst
1411 };
1412 let request_size = request_value_reader
1413 .seek(std::io::SeekFrom::End(0))
1414 .unwrap();
1415 request_value_reader
1416 .seek(std::io::SeekFrom::Start(0))
1417 .unwrap();
1418
1419 loop {
1420 let token = match self
1421 .hub
1422 .auth
1423 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1424 .await
1425 {
1426 Ok(token) => token,
1427 Err(e) => match dlg.token(e) {
1428 Ok(token) => token,
1429 Err(e) => {
1430 dlg.finished(false);
1431 return Err(common::Error::MissingToken(e));
1432 }
1433 },
1434 };
1435 request_value_reader
1436 .seek(std::io::SeekFrom::Start(0))
1437 .unwrap();
1438 let mut req_result = {
1439 let client = &self.hub.client;
1440 dlg.pre_request();
1441 let mut req_builder = hyper::Request::builder()
1442 .method(hyper::Method::POST)
1443 .uri(url.as_str())
1444 .header(USER_AGENT, self.hub._user_agent.clone());
1445
1446 if let Some(token) = token.as_ref() {
1447 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1448 }
1449
1450 let request = req_builder
1451 .header(CONTENT_TYPE, json_mime_type.to_string())
1452 .header(CONTENT_LENGTH, request_size as u64)
1453 .body(common::to_body(
1454 request_value_reader.get_ref().clone().into(),
1455 ));
1456
1457 client.request(request.unwrap()).await
1458 };
1459
1460 match req_result {
1461 Err(err) => {
1462 if let common::Retry::After(d) = dlg.http_error(&err) {
1463 sleep(d).await;
1464 continue;
1465 }
1466 dlg.finished(false);
1467 return Err(common::Error::HttpError(err));
1468 }
1469 Ok(res) => {
1470 let (mut parts, body) = res.into_parts();
1471 let mut body = common::Body::new(body);
1472 if !parts.status.is_success() {
1473 let bytes = common::to_bytes(body).await.unwrap_or_default();
1474 let error = serde_json::from_str(&common::to_string(&bytes));
1475 let response = common::to_response(parts, bytes.into());
1476
1477 if let common::Retry::After(d) =
1478 dlg.http_failure(&response, error.as_ref().ok())
1479 {
1480 sleep(d).await;
1481 continue;
1482 }
1483
1484 dlg.finished(false);
1485
1486 return Err(match error {
1487 Ok(value) => common::Error::BadRequest(value),
1488 _ => common::Error::Failure(response),
1489 });
1490 }
1491 let response = {
1492 let bytes = common::to_bytes(body).await.unwrap_or_default();
1493 let encoded = common::to_string(&bytes);
1494 match serde_json::from_str(&encoded) {
1495 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1496 Err(error) => {
1497 dlg.response_json_decode_error(&encoded, &error);
1498 return Err(common::Error::JsonDecodeError(
1499 encoded.to_string(),
1500 error,
1501 ));
1502 }
1503 }
1504 };
1505
1506 dlg.finished(true);
1507 return Ok(response);
1508 }
1509 }
1510 }
1511 }
1512
1513 ///
1514 /// Sets the *request* property to the given value.
1515 ///
1516 /// Even though the property as already been set when instantiating this call,
1517 /// we provide this method for API completeness.
1518 pub fn request(
1519 mut self,
1520 new_value: AnalyzeEntitySentimentRequest,
1521 ) -> DocumentAnalyzeEntitySentimentCall<'a, C> {
1522 self._request = new_value;
1523 self
1524 }
1525 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1526 /// while executing the actual API request.
1527 ///
1528 /// ````text
1529 /// It should be used to handle progress information, and to implement a certain level of resilience.
1530 /// ````
1531 ///
1532 /// Sets the *delegate* property to the given value.
1533 pub fn delegate(
1534 mut self,
1535 new_value: &'a mut dyn common::Delegate,
1536 ) -> DocumentAnalyzeEntitySentimentCall<'a, C> {
1537 self._delegate = Some(new_value);
1538 self
1539 }
1540
1541 /// Set any additional parameter of the query string used in the request.
1542 /// It should be used to set parameters which are not yet available through their own
1543 /// setters.
1544 ///
1545 /// Please note that this method must not be used to set any of the known parameters
1546 /// which have their own setter method. If done anyway, the request will fail.
1547 ///
1548 /// # Additional Parameters
1549 ///
1550 /// * *$.xgafv* (query-string) - V1 error format.
1551 /// * *access_token* (query-string) - OAuth access token.
1552 /// * *alt* (query-string) - Data format for response.
1553 /// * *callback* (query-string) - JSONP
1554 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1555 /// * *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.
1556 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1557 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1558 /// * *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.
1559 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1560 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1561 pub fn param<T>(mut self, name: T, value: T) -> DocumentAnalyzeEntitySentimentCall<'a, C>
1562 where
1563 T: AsRef<str>,
1564 {
1565 self._additional_params
1566 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1567 self
1568 }
1569
1570 /// Identifies the authorization scope for the method you are building.
1571 ///
1572 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1573 /// [`Scope::CloudPlatform`].
1574 ///
1575 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1576 /// tokens for more than one scope.
1577 ///
1578 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1579 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1580 /// sufficient, a read-write scope will do as well.
1581 pub fn add_scope<St>(mut self, scope: St) -> DocumentAnalyzeEntitySentimentCall<'a, C>
1582 where
1583 St: AsRef<str>,
1584 {
1585 self._scopes.insert(String::from(scope.as_ref()));
1586 self
1587 }
1588 /// Identifies the authorization scope(s) for the method you are building.
1589 ///
1590 /// See [`Self::add_scope()`] for details.
1591 pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentAnalyzeEntitySentimentCall<'a, C>
1592 where
1593 I: IntoIterator<Item = St>,
1594 St: AsRef<str>,
1595 {
1596 self._scopes
1597 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1598 self
1599 }
1600
1601 /// Removes all scopes, and no default scope will be used either.
1602 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1603 /// for details).
1604 pub fn clear_scopes(mut self) -> DocumentAnalyzeEntitySentimentCall<'a, C> {
1605 self._scopes.clear();
1606 self
1607 }
1608}
1609
1610/// Analyzes the sentiment of the provided text.
1611///
1612/// A builder for the *analyzeSentiment* method supported by a *document* resource.
1613/// It is not used directly, but through a [`DocumentMethods`] instance.
1614///
1615/// # Example
1616///
1617/// Instantiate a resource method builder
1618///
1619/// ```test_harness,no_run
1620/// # extern crate hyper;
1621/// # extern crate hyper_rustls;
1622/// # extern crate google_language1 as language1;
1623/// use language1::api::AnalyzeSentimentRequest;
1624/// # async fn dox() {
1625/// # use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1626///
1627/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1628/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1629/// # .with_native_roots()
1630/// # .unwrap()
1631/// # .https_only()
1632/// # .enable_http2()
1633/// # .build();
1634///
1635/// # let executor = hyper_util::rt::TokioExecutor::new();
1636/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1637/// # secret,
1638/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1639/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1640/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1641/// # ),
1642/// # ).build().await.unwrap();
1643///
1644/// # let client = hyper_util::client::legacy::Client::builder(
1645/// # hyper_util::rt::TokioExecutor::new()
1646/// # )
1647/// # .build(
1648/// # hyper_rustls::HttpsConnectorBuilder::new()
1649/// # .with_native_roots()
1650/// # .unwrap()
1651/// # .https_or_http()
1652/// # .enable_http2()
1653/// # .build()
1654/// # );
1655/// # let mut hub = CloudNaturalLanguage::new(client, auth);
1656/// // As the method needs a request, you would usually fill it with the desired information
1657/// // into the respective structure. Some of the parts shown here might not be applicable !
1658/// // Values shown here are possibly random and not representative !
1659/// let mut req = AnalyzeSentimentRequest::default();
1660///
1661/// // You can configure optional parameters by calling the respective setters at will, and
1662/// // execute the final call using `doit()`.
1663/// // Values shown here are possibly random and not representative !
1664/// let result = hub.documents().analyze_sentiment(req)
1665/// .doit().await;
1666/// # }
1667/// ```
1668pub struct DocumentAnalyzeSentimentCall<'a, C>
1669where
1670 C: 'a,
1671{
1672 hub: &'a CloudNaturalLanguage<C>,
1673 _request: AnalyzeSentimentRequest,
1674 _delegate: Option<&'a mut dyn common::Delegate>,
1675 _additional_params: HashMap<String, String>,
1676 _scopes: BTreeSet<String>,
1677}
1678
1679impl<'a, C> common::CallBuilder for DocumentAnalyzeSentimentCall<'a, C> {}
1680
1681impl<'a, C> DocumentAnalyzeSentimentCall<'a, C>
1682where
1683 C: common::Connector,
1684{
1685 /// Perform the operation you have build so far.
1686 pub async fn doit(mut self) -> common::Result<(common::Response, AnalyzeSentimentResponse)> {
1687 use std::borrow::Cow;
1688 use std::io::{Read, Seek};
1689
1690 use common::{url::Params, ToParts};
1691 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1692
1693 let mut dd = common::DefaultDelegate;
1694 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1695 dlg.begin(common::MethodInfo {
1696 id: "language.documents.analyzeSentiment",
1697 http_method: hyper::Method::POST,
1698 });
1699
1700 for &field in ["alt"].iter() {
1701 if self._additional_params.contains_key(field) {
1702 dlg.finished(false);
1703 return Err(common::Error::FieldClash(field));
1704 }
1705 }
1706
1707 let mut params = Params::with_capacity(3 + self._additional_params.len());
1708
1709 params.extend(self._additional_params.iter());
1710
1711 params.push("alt", "json");
1712 let mut url = self.hub._base_url.clone() + "v1/documents:analyzeSentiment";
1713 if self._scopes.is_empty() {
1714 self._scopes
1715 .insert(Scope::CloudPlatform.as_ref().to_string());
1716 }
1717
1718 let url = params.parse_with_url(&url);
1719
1720 let mut json_mime_type = mime::APPLICATION_JSON;
1721 let mut request_value_reader = {
1722 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1723 common::remove_json_null_values(&mut value);
1724 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1725 serde_json::to_writer(&mut dst, &value).unwrap();
1726 dst
1727 };
1728 let request_size = request_value_reader
1729 .seek(std::io::SeekFrom::End(0))
1730 .unwrap();
1731 request_value_reader
1732 .seek(std::io::SeekFrom::Start(0))
1733 .unwrap();
1734
1735 loop {
1736 let token = match self
1737 .hub
1738 .auth
1739 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1740 .await
1741 {
1742 Ok(token) => token,
1743 Err(e) => match dlg.token(e) {
1744 Ok(token) => token,
1745 Err(e) => {
1746 dlg.finished(false);
1747 return Err(common::Error::MissingToken(e));
1748 }
1749 },
1750 };
1751 request_value_reader
1752 .seek(std::io::SeekFrom::Start(0))
1753 .unwrap();
1754 let mut req_result = {
1755 let client = &self.hub.client;
1756 dlg.pre_request();
1757 let mut req_builder = hyper::Request::builder()
1758 .method(hyper::Method::POST)
1759 .uri(url.as_str())
1760 .header(USER_AGENT, self.hub._user_agent.clone());
1761
1762 if let Some(token) = token.as_ref() {
1763 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1764 }
1765
1766 let request = req_builder
1767 .header(CONTENT_TYPE, json_mime_type.to_string())
1768 .header(CONTENT_LENGTH, request_size as u64)
1769 .body(common::to_body(
1770 request_value_reader.get_ref().clone().into(),
1771 ));
1772
1773 client.request(request.unwrap()).await
1774 };
1775
1776 match req_result {
1777 Err(err) => {
1778 if let common::Retry::After(d) = dlg.http_error(&err) {
1779 sleep(d).await;
1780 continue;
1781 }
1782 dlg.finished(false);
1783 return Err(common::Error::HttpError(err));
1784 }
1785 Ok(res) => {
1786 let (mut parts, body) = res.into_parts();
1787 let mut body = common::Body::new(body);
1788 if !parts.status.is_success() {
1789 let bytes = common::to_bytes(body).await.unwrap_or_default();
1790 let error = serde_json::from_str(&common::to_string(&bytes));
1791 let response = common::to_response(parts, bytes.into());
1792
1793 if let common::Retry::After(d) =
1794 dlg.http_failure(&response, error.as_ref().ok())
1795 {
1796 sleep(d).await;
1797 continue;
1798 }
1799
1800 dlg.finished(false);
1801
1802 return Err(match error {
1803 Ok(value) => common::Error::BadRequest(value),
1804 _ => common::Error::Failure(response),
1805 });
1806 }
1807 let response = {
1808 let bytes = common::to_bytes(body).await.unwrap_or_default();
1809 let encoded = common::to_string(&bytes);
1810 match serde_json::from_str(&encoded) {
1811 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1812 Err(error) => {
1813 dlg.response_json_decode_error(&encoded, &error);
1814 return Err(common::Error::JsonDecodeError(
1815 encoded.to_string(),
1816 error,
1817 ));
1818 }
1819 }
1820 };
1821
1822 dlg.finished(true);
1823 return Ok(response);
1824 }
1825 }
1826 }
1827 }
1828
1829 ///
1830 /// Sets the *request* property to the given value.
1831 ///
1832 /// Even though the property as already been set when instantiating this call,
1833 /// we provide this method for API completeness.
1834 pub fn request(
1835 mut self,
1836 new_value: AnalyzeSentimentRequest,
1837 ) -> DocumentAnalyzeSentimentCall<'a, C> {
1838 self._request = new_value;
1839 self
1840 }
1841 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1842 /// while executing the actual API request.
1843 ///
1844 /// ````text
1845 /// It should be used to handle progress information, and to implement a certain level of resilience.
1846 /// ````
1847 ///
1848 /// Sets the *delegate* property to the given value.
1849 pub fn delegate(
1850 mut self,
1851 new_value: &'a mut dyn common::Delegate,
1852 ) -> DocumentAnalyzeSentimentCall<'a, C> {
1853 self._delegate = Some(new_value);
1854 self
1855 }
1856
1857 /// Set any additional parameter of the query string used in the request.
1858 /// It should be used to set parameters which are not yet available through their own
1859 /// setters.
1860 ///
1861 /// Please note that this method must not be used to set any of the known parameters
1862 /// which have their own setter method. If done anyway, the request will fail.
1863 ///
1864 /// # Additional Parameters
1865 ///
1866 /// * *$.xgafv* (query-string) - V1 error format.
1867 /// * *access_token* (query-string) - OAuth access token.
1868 /// * *alt* (query-string) - Data format for response.
1869 /// * *callback* (query-string) - JSONP
1870 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1871 /// * *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.
1872 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1873 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1874 /// * *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.
1875 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1876 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1877 pub fn param<T>(mut self, name: T, value: T) -> DocumentAnalyzeSentimentCall<'a, C>
1878 where
1879 T: AsRef<str>,
1880 {
1881 self._additional_params
1882 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1883 self
1884 }
1885
1886 /// Identifies the authorization scope for the method you are building.
1887 ///
1888 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1889 /// [`Scope::CloudPlatform`].
1890 ///
1891 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1892 /// tokens for more than one scope.
1893 ///
1894 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1895 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1896 /// sufficient, a read-write scope will do as well.
1897 pub fn add_scope<St>(mut self, scope: St) -> DocumentAnalyzeSentimentCall<'a, C>
1898 where
1899 St: AsRef<str>,
1900 {
1901 self._scopes.insert(String::from(scope.as_ref()));
1902 self
1903 }
1904 /// Identifies the authorization scope(s) for the method you are building.
1905 ///
1906 /// See [`Self::add_scope()`] for details.
1907 pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentAnalyzeSentimentCall<'a, C>
1908 where
1909 I: IntoIterator<Item = St>,
1910 St: AsRef<str>,
1911 {
1912 self._scopes
1913 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1914 self
1915 }
1916
1917 /// Removes all scopes, and no default scope will be used either.
1918 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1919 /// for details).
1920 pub fn clear_scopes(mut self) -> DocumentAnalyzeSentimentCall<'a, C> {
1921 self._scopes.clear();
1922 self
1923 }
1924}
1925
1926/// Analyzes the syntax of the text and provides sentence boundaries and tokenization along with part of speech tags, dependency trees, and other properties.
1927///
1928/// A builder for the *analyzeSyntax* method supported by a *document* resource.
1929/// It is not used directly, but through a [`DocumentMethods`] instance.
1930///
1931/// # Example
1932///
1933/// Instantiate a resource method builder
1934///
1935/// ```test_harness,no_run
1936/// # extern crate hyper;
1937/// # extern crate hyper_rustls;
1938/// # extern crate google_language1 as language1;
1939/// use language1::api::AnalyzeSyntaxRequest;
1940/// # async fn dox() {
1941/// # use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1942///
1943/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1944/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1945/// # .with_native_roots()
1946/// # .unwrap()
1947/// # .https_only()
1948/// # .enable_http2()
1949/// # .build();
1950///
1951/// # let executor = hyper_util::rt::TokioExecutor::new();
1952/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1953/// # secret,
1954/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1955/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1956/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1957/// # ),
1958/// # ).build().await.unwrap();
1959///
1960/// # let client = hyper_util::client::legacy::Client::builder(
1961/// # hyper_util::rt::TokioExecutor::new()
1962/// # )
1963/// # .build(
1964/// # hyper_rustls::HttpsConnectorBuilder::new()
1965/// # .with_native_roots()
1966/// # .unwrap()
1967/// # .https_or_http()
1968/// # .enable_http2()
1969/// # .build()
1970/// # );
1971/// # let mut hub = CloudNaturalLanguage::new(client, auth);
1972/// // As the method needs a request, you would usually fill it with the desired information
1973/// // into the respective structure. Some of the parts shown here might not be applicable !
1974/// // Values shown here are possibly random and not representative !
1975/// let mut req = AnalyzeSyntaxRequest::default();
1976///
1977/// // You can configure optional parameters by calling the respective setters at will, and
1978/// // execute the final call using `doit()`.
1979/// // Values shown here are possibly random and not representative !
1980/// let result = hub.documents().analyze_syntax(req)
1981/// .doit().await;
1982/// # }
1983/// ```
1984pub struct DocumentAnalyzeSyntaxCall<'a, C>
1985where
1986 C: 'a,
1987{
1988 hub: &'a CloudNaturalLanguage<C>,
1989 _request: AnalyzeSyntaxRequest,
1990 _delegate: Option<&'a mut dyn common::Delegate>,
1991 _additional_params: HashMap<String, String>,
1992 _scopes: BTreeSet<String>,
1993}
1994
1995impl<'a, C> common::CallBuilder for DocumentAnalyzeSyntaxCall<'a, C> {}
1996
1997impl<'a, C> DocumentAnalyzeSyntaxCall<'a, C>
1998where
1999 C: common::Connector,
2000{
2001 /// Perform the operation you have build so far.
2002 pub async fn doit(mut self) -> common::Result<(common::Response, AnalyzeSyntaxResponse)> {
2003 use std::borrow::Cow;
2004 use std::io::{Read, Seek};
2005
2006 use common::{url::Params, ToParts};
2007 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2008
2009 let mut dd = common::DefaultDelegate;
2010 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2011 dlg.begin(common::MethodInfo {
2012 id: "language.documents.analyzeSyntax",
2013 http_method: hyper::Method::POST,
2014 });
2015
2016 for &field in ["alt"].iter() {
2017 if self._additional_params.contains_key(field) {
2018 dlg.finished(false);
2019 return Err(common::Error::FieldClash(field));
2020 }
2021 }
2022
2023 let mut params = Params::with_capacity(3 + self._additional_params.len());
2024
2025 params.extend(self._additional_params.iter());
2026
2027 params.push("alt", "json");
2028 let mut url = self.hub._base_url.clone() + "v1/documents:analyzeSyntax";
2029 if self._scopes.is_empty() {
2030 self._scopes
2031 .insert(Scope::CloudPlatform.as_ref().to_string());
2032 }
2033
2034 let url = params.parse_with_url(&url);
2035
2036 let mut json_mime_type = mime::APPLICATION_JSON;
2037 let mut request_value_reader = {
2038 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2039 common::remove_json_null_values(&mut value);
2040 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2041 serde_json::to_writer(&mut dst, &value).unwrap();
2042 dst
2043 };
2044 let request_size = request_value_reader
2045 .seek(std::io::SeekFrom::End(0))
2046 .unwrap();
2047 request_value_reader
2048 .seek(std::io::SeekFrom::Start(0))
2049 .unwrap();
2050
2051 loop {
2052 let token = match self
2053 .hub
2054 .auth
2055 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2056 .await
2057 {
2058 Ok(token) => token,
2059 Err(e) => match dlg.token(e) {
2060 Ok(token) => token,
2061 Err(e) => {
2062 dlg.finished(false);
2063 return Err(common::Error::MissingToken(e));
2064 }
2065 },
2066 };
2067 request_value_reader
2068 .seek(std::io::SeekFrom::Start(0))
2069 .unwrap();
2070 let mut req_result = {
2071 let client = &self.hub.client;
2072 dlg.pre_request();
2073 let mut req_builder = hyper::Request::builder()
2074 .method(hyper::Method::POST)
2075 .uri(url.as_str())
2076 .header(USER_AGENT, self.hub._user_agent.clone());
2077
2078 if let Some(token) = token.as_ref() {
2079 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2080 }
2081
2082 let request = req_builder
2083 .header(CONTENT_TYPE, json_mime_type.to_string())
2084 .header(CONTENT_LENGTH, request_size as u64)
2085 .body(common::to_body(
2086 request_value_reader.get_ref().clone().into(),
2087 ));
2088
2089 client.request(request.unwrap()).await
2090 };
2091
2092 match req_result {
2093 Err(err) => {
2094 if let common::Retry::After(d) = dlg.http_error(&err) {
2095 sleep(d).await;
2096 continue;
2097 }
2098 dlg.finished(false);
2099 return Err(common::Error::HttpError(err));
2100 }
2101 Ok(res) => {
2102 let (mut parts, body) = res.into_parts();
2103 let mut body = common::Body::new(body);
2104 if !parts.status.is_success() {
2105 let bytes = common::to_bytes(body).await.unwrap_or_default();
2106 let error = serde_json::from_str(&common::to_string(&bytes));
2107 let response = common::to_response(parts, bytes.into());
2108
2109 if let common::Retry::After(d) =
2110 dlg.http_failure(&response, error.as_ref().ok())
2111 {
2112 sleep(d).await;
2113 continue;
2114 }
2115
2116 dlg.finished(false);
2117
2118 return Err(match error {
2119 Ok(value) => common::Error::BadRequest(value),
2120 _ => common::Error::Failure(response),
2121 });
2122 }
2123 let response = {
2124 let bytes = common::to_bytes(body).await.unwrap_or_default();
2125 let encoded = common::to_string(&bytes);
2126 match serde_json::from_str(&encoded) {
2127 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2128 Err(error) => {
2129 dlg.response_json_decode_error(&encoded, &error);
2130 return Err(common::Error::JsonDecodeError(
2131 encoded.to_string(),
2132 error,
2133 ));
2134 }
2135 }
2136 };
2137
2138 dlg.finished(true);
2139 return Ok(response);
2140 }
2141 }
2142 }
2143 }
2144
2145 ///
2146 /// Sets the *request* property to the given value.
2147 ///
2148 /// Even though the property as already been set when instantiating this call,
2149 /// we provide this method for API completeness.
2150 pub fn request(mut self, new_value: AnalyzeSyntaxRequest) -> DocumentAnalyzeSyntaxCall<'a, C> {
2151 self._request = new_value;
2152 self
2153 }
2154 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2155 /// while executing the actual API request.
2156 ///
2157 /// ````text
2158 /// It should be used to handle progress information, and to implement a certain level of resilience.
2159 /// ````
2160 ///
2161 /// Sets the *delegate* property to the given value.
2162 pub fn delegate(
2163 mut self,
2164 new_value: &'a mut dyn common::Delegate,
2165 ) -> DocumentAnalyzeSyntaxCall<'a, C> {
2166 self._delegate = Some(new_value);
2167 self
2168 }
2169
2170 /// Set any additional parameter of the query string used in the request.
2171 /// It should be used to set parameters which are not yet available through their own
2172 /// setters.
2173 ///
2174 /// Please note that this method must not be used to set any of the known parameters
2175 /// which have their own setter method. If done anyway, the request will fail.
2176 ///
2177 /// # Additional Parameters
2178 ///
2179 /// * *$.xgafv* (query-string) - V1 error format.
2180 /// * *access_token* (query-string) - OAuth access token.
2181 /// * *alt* (query-string) - Data format for response.
2182 /// * *callback* (query-string) - JSONP
2183 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2184 /// * *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.
2185 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2186 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2187 /// * *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.
2188 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2189 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2190 pub fn param<T>(mut self, name: T, value: T) -> DocumentAnalyzeSyntaxCall<'a, C>
2191 where
2192 T: AsRef<str>,
2193 {
2194 self._additional_params
2195 .insert(name.as_ref().to_string(), value.as_ref().to_string());
2196 self
2197 }
2198
2199 /// Identifies the authorization scope for the method you are building.
2200 ///
2201 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2202 /// [`Scope::CloudPlatform`].
2203 ///
2204 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2205 /// tokens for more than one scope.
2206 ///
2207 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2208 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2209 /// sufficient, a read-write scope will do as well.
2210 pub fn add_scope<St>(mut self, scope: St) -> DocumentAnalyzeSyntaxCall<'a, C>
2211 where
2212 St: AsRef<str>,
2213 {
2214 self._scopes.insert(String::from(scope.as_ref()));
2215 self
2216 }
2217 /// Identifies the authorization scope(s) for the method you are building.
2218 ///
2219 /// See [`Self::add_scope()`] for details.
2220 pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentAnalyzeSyntaxCall<'a, C>
2221 where
2222 I: IntoIterator<Item = St>,
2223 St: AsRef<str>,
2224 {
2225 self._scopes
2226 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2227 self
2228 }
2229
2230 /// Removes all scopes, and no default scope will be used either.
2231 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2232 /// for details).
2233 pub fn clear_scopes(mut self) -> DocumentAnalyzeSyntaxCall<'a, C> {
2234 self._scopes.clear();
2235 self
2236 }
2237}
2238
2239/// A convenience method that provides all the features that analyzeSentiment, analyzeEntities, and analyzeSyntax provide in one call.
2240///
2241/// A builder for the *annotateText* method supported by a *document* resource.
2242/// It is not used directly, but through a [`DocumentMethods`] instance.
2243///
2244/// # Example
2245///
2246/// Instantiate a resource method builder
2247///
2248/// ```test_harness,no_run
2249/// # extern crate hyper;
2250/// # extern crate hyper_rustls;
2251/// # extern crate google_language1 as language1;
2252/// use language1::api::AnnotateTextRequest;
2253/// # async fn dox() {
2254/// # use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2255///
2256/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2257/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2258/// # .with_native_roots()
2259/// # .unwrap()
2260/// # .https_only()
2261/// # .enable_http2()
2262/// # .build();
2263///
2264/// # let executor = hyper_util::rt::TokioExecutor::new();
2265/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2266/// # secret,
2267/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2268/// # yup_oauth2::client::CustomHyperClientBuilder::from(
2269/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
2270/// # ),
2271/// # ).build().await.unwrap();
2272///
2273/// # let client = hyper_util::client::legacy::Client::builder(
2274/// # hyper_util::rt::TokioExecutor::new()
2275/// # )
2276/// # .build(
2277/// # hyper_rustls::HttpsConnectorBuilder::new()
2278/// # .with_native_roots()
2279/// # .unwrap()
2280/// # .https_or_http()
2281/// # .enable_http2()
2282/// # .build()
2283/// # );
2284/// # let mut hub = CloudNaturalLanguage::new(client, auth);
2285/// // As the method needs a request, you would usually fill it with the desired information
2286/// // into the respective structure. Some of the parts shown here might not be applicable !
2287/// // Values shown here are possibly random and not representative !
2288/// let mut req = AnnotateTextRequest::default();
2289///
2290/// // You can configure optional parameters by calling the respective setters at will, and
2291/// // execute the final call using `doit()`.
2292/// // Values shown here are possibly random and not representative !
2293/// let result = hub.documents().annotate_text(req)
2294/// .doit().await;
2295/// # }
2296/// ```
2297pub struct DocumentAnnotateTextCall<'a, C>
2298where
2299 C: 'a,
2300{
2301 hub: &'a CloudNaturalLanguage<C>,
2302 _request: AnnotateTextRequest,
2303 _delegate: Option<&'a mut dyn common::Delegate>,
2304 _additional_params: HashMap<String, String>,
2305 _scopes: BTreeSet<String>,
2306}
2307
2308impl<'a, C> common::CallBuilder for DocumentAnnotateTextCall<'a, C> {}
2309
2310impl<'a, C> DocumentAnnotateTextCall<'a, C>
2311where
2312 C: common::Connector,
2313{
2314 /// Perform the operation you have build so far.
2315 pub async fn doit(mut self) -> common::Result<(common::Response, AnnotateTextResponse)> {
2316 use std::borrow::Cow;
2317 use std::io::{Read, Seek};
2318
2319 use common::{url::Params, ToParts};
2320 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2321
2322 let mut dd = common::DefaultDelegate;
2323 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2324 dlg.begin(common::MethodInfo {
2325 id: "language.documents.annotateText",
2326 http_method: hyper::Method::POST,
2327 });
2328
2329 for &field in ["alt"].iter() {
2330 if self._additional_params.contains_key(field) {
2331 dlg.finished(false);
2332 return Err(common::Error::FieldClash(field));
2333 }
2334 }
2335
2336 let mut params = Params::with_capacity(3 + self._additional_params.len());
2337
2338 params.extend(self._additional_params.iter());
2339
2340 params.push("alt", "json");
2341 let mut url = self.hub._base_url.clone() + "v1/documents:annotateText";
2342 if self._scopes.is_empty() {
2343 self._scopes
2344 .insert(Scope::CloudPlatform.as_ref().to_string());
2345 }
2346
2347 let url = params.parse_with_url(&url);
2348
2349 let mut json_mime_type = mime::APPLICATION_JSON;
2350 let mut request_value_reader = {
2351 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2352 common::remove_json_null_values(&mut value);
2353 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2354 serde_json::to_writer(&mut dst, &value).unwrap();
2355 dst
2356 };
2357 let request_size = request_value_reader
2358 .seek(std::io::SeekFrom::End(0))
2359 .unwrap();
2360 request_value_reader
2361 .seek(std::io::SeekFrom::Start(0))
2362 .unwrap();
2363
2364 loop {
2365 let token = match self
2366 .hub
2367 .auth
2368 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2369 .await
2370 {
2371 Ok(token) => token,
2372 Err(e) => match dlg.token(e) {
2373 Ok(token) => token,
2374 Err(e) => {
2375 dlg.finished(false);
2376 return Err(common::Error::MissingToken(e));
2377 }
2378 },
2379 };
2380 request_value_reader
2381 .seek(std::io::SeekFrom::Start(0))
2382 .unwrap();
2383 let mut req_result = {
2384 let client = &self.hub.client;
2385 dlg.pre_request();
2386 let mut req_builder = hyper::Request::builder()
2387 .method(hyper::Method::POST)
2388 .uri(url.as_str())
2389 .header(USER_AGENT, self.hub._user_agent.clone());
2390
2391 if let Some(token) = token.as_ref() {
2392 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2393 }
2394
2395 let request = req_builder
2396 .header(CONTENT_TYPE, json_mime_type.to_string())
2397 .header(CONTENT_LENGTH, request_size as u64)
2398 .body(common::to_body(
2399 request_value_reader.get_ref().clone().into(),
2400 ));
2401
2402 client.request(request.unwrap()).await
2403 };
2404
2405 match req_result {
2406 Err(err) => {
2407 if let common::Retry::After(d) = dlg.http_error(&err) {
2408 sleep(d).await;
2409 continue;
2410 }
2411 dlg.finished(false);
2412 return Err(common::Error::HttpError(err));
2413 }
2414 Ok(res) => {
2415 let (mut parts, body) = res.into_parts();
2416 let mut body = common::Body::new(body);
2417 if !parts.status.is_success() {
2418 let bytes = common::to_bytes(body).await.unwrap_or_default();
2419 let error = serde_json::from_str(&common::to_string(&bytes));
2420 let response = common::to_response(parts, bytes.into());
2421
2422 if let common::Retry::After(d) =
2423 dlg.http_failure(&response, error.as_ref().ok())
2424 {
2425 sleep(d).await;
2426 continue;
2427 }
2428
2429 dlg.finished(false);
2430
2431 return Err(match error {
2432 Ok(value) => common::Error::BadRequest(value),
2433 _ => common::Error::Failure(response),
2434 });
2435 }
2436 let response = {
2437 let bytes = common::to_bytes(body).await.unwrap_or_default();
2438 let encoded = common::to_string(&bytes);
2439 match serde_json::from_str(&encoded) {
2440 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2441 Err(error) => {
2442 dlg.response_json_decode_error(&encoded, &error);
2443 return Err(common::Error::JsonDecodeError(
2444 encoded.to_string(),
2445 error,
2446 ));
2447 }
2448 }
2449 };
2450
2451 dlg.finished(true);
2452 return Ok(response);
2453 }
2454 }
2455 }
2456 }
2457
2458 ///
2459 /// Sets the *request* property to the given value.
2460 ///
2461 /// Even though the property as already been set when instantiating this call,
2462 /// we provide this method for API completeness.
2463 pub fn request(mut self, new_value: AnnotateTextRequest) -> DocumentAnnotateTextCall<'a, C> {
2464 self._request = new_value;
2465 self
2466 }
2467 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2468 /// while executing the actual API request.
2469 ///
2470 /// ````text
2471 /// It should be used to handle progress information, and to implement a certain level of resilience.
2472 /// ````
2473 ///
2474 /// Sets the *delegate* property to the given value.
2475 pub fn delegate(
2476 mut self,
2477 new_value: &'a mut dyn common::Delegate,
2478 ) -> DocumentAnnotateTextCall<'a, C> {
2479 self._delegate = Some(new_value);
2480 self
2481 }
2482
2483 /// Set any additional parameter of the query string used in the request.
2484 /// It should be used to set parameters which are not yet available through their own
2485 /// setters.
2486 ///
2487 /// Please note that this method must not be used to set any of the known parameters
2488 /// which have their own setter method. If done anyway, the request will fail.
2489 ///
2490 /// # Additional Parameters
2491 ///
2492 /// * *$.xgafv* (query-string) - V1 error format.
2493 /// * *access_token* (query-string) - OAuth access token.
2494 /// * *alt* (query-string) - Data format for response.
2495 /// * *callback* (query-string) - JSONP
2496 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2497 /// * *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.
2498 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2499 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2500 /// * *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.
2501 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2502 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2503 pub fn param<T>(mut self, name: T, value: T) -> DocumentAnnotateTextCall<'a, C>
2504 where
2505 T: AsRef<str>,
2506 {
2507 self._additional_params
2508 .insert(name.as_ref().to_string(), value.as_ref().to_string());
2509 self
2510 }
2511
2512 /// Identifies the authorization scope for the method you are building.
2513 ///
2514 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2515 /// [`Scope::CloudPlatform`].
2516 ///
2517 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2518 /// tokens for more than one scope.
2519 ///
2520 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2521 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2522 /// sufficient, a read-write scope will do as well.
2523 pub fn add_scope<St>(mut self, scope: St) -> DocumentAnnotateTextCall<'a, C>
2524 where
2525 St: AsRef<str>,
2526 {
2527 self._scopes.insert(String::from(scope.as_ref()));
2528 self
2529 }
2530 /// Identifies the authorization scope(s) for the method you are building.
2531 ///
2532 /// See [`Self::add_scope()`] for details.
2533 pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentAnnotateTextCall<'a, C>
2534 where
2535 I: IntoIterator<Item = St>,
2536 St: AsRef<str>,
2537 {
2538 self._scopes
2539 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2540 self
2541 }
2542
2543 /// Removes all scopes, and no default scope will be used either.
2544 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2545 /// for details).
2546 pub fn clear_scopes(mut self) -> DocumentAnnotateTextCall<'a, C> {
2547 self._scopes.clear();
2548 self
2549 }
2550}
2551
2552/// Classifies a document into categories.
2553///
2554/// A builder for the *classifyText* method supported by a *document* resource.
2555/// It is not used directly, but through a [`DocumentMethods`] instance.
2556///
2557/// # Example
2558///
2559/// Instantiate a resource method builder
2560///
2561/// ```test_harness,no_run
2562/// # extern crate hyper;
2563/// # extern crate hyper_rustls;
2564/// # extern crate google_language1 as language1;
2565/// use language1::api::ClassifyTextRequest;
2566/// # async fn dox() {
2567/// # use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2568///
2569/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2570/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2571/// # .with_native_roots()
2572/// # .unwrap()
2573/// # .https_only()
2574/// # .enable_http2()
2575/// # .build();
2576///
2577/// # let executor = hyper_util::rt::TokioExecutor::new();
2578/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2579/// # secret,
2580/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2581/// # yup_oauth2::client::CustomHyperClientBuilder::from(
2582/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
2583/// # ),
2584/// # ).build().await.unwrap();
2585///
2586/// # let client = hyper_util::client::legacy::Client::builder(
2587/// # hyper_util::rt::TokioExecutor::new()
2588/// # )
2589/// # .build(
2590/// # hyper_rustls::HttpsConnectorBuilder::new()
2591/// # .with_native_roots()
2592/// # .unwrap()
2593/// # .https_or_http()
2594/// # .enable_http2()
2595/// # .build()
2596/// # );
2597/// # let mut hub = CloudNaturalLanguage::new(client, auth);
2598/// // As the method needs a request, you would usually fill it with the desired information
2599/// // into the respective structure. Some of the parts shown here might not be applicable !
2600/// // Values shown here are possibly random and not representative !
2601/// let mut req = ClassifyTextRequest::default();
2602///
2603/// // You can configure optional parameters by calling the respective setters at will, and
2604/// // execute the final call using `doit()`.
2605/// // Values shown here are possibly random and not representative !
2606/// let result = hub.documents().classify_text(req)
2607/// .doit().await;
2608/// # }
2609/// ```
2610pub struct DocumentClassifyTextCall<'a, C>
2611where
2612 C: 'a,
2613{
2614 hub: &'a CloudNaturalLanguage<C>,
2615 _request: ClassifyTextRequest,
2616 _delegate: Option<&'a mut dyn common::Delegate>,
2617 _additional_params: HashMap<String, String>,
2618 _scopes: BTreeSet<String>,
2619}
2620
2621impl<'a, C> common::CallBuilder for DocumentClassifyTextCall<'a, C> {}
2622
2623impl<'a, C> DocumentClassifyTextCall<'a, C>
2624where
2625 C: common::Connector,
2626{
2627 /// Perform the operation you have build so far.
2628 pub async fn doit(mut self) -> common::Result<(common::Response, ClassifyTextResponse)> {
2629 use std::borrow::Cow;
2630 use std::io::{Read, Seek};
2631
2632 use common::{url::Params, ToParts};
2633 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2634
2635 let mut dd = common::DefaultDelegate;
2636 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2637 dlg.begin(common::MethodInfo {
2638 id: "language.documents.classifyText",
2639 http_method: hyper::Method::POST,
2640 });
2641
2642 for &field in ["alt"].iter() {
2643 if self._additional_params.contains_key(field) {
2644 dlg.finished(false);
2645 return Err(common::Error::FieldClash(field));
2646 }
2647 }
2648
2649 let mut params = Params::with_capacity(3 + self._additional_params.len());
2650
2651 params.extend(self._additional_params.iter());
2652
2653 params.push("alt", "json");
2654 let mut url = self.hub._base_url.clone() + "v1/documents:classifyText";
2655 if self._scopes.is_empty() {
2656 self._scopes
2657 .insert(Scope::CloudPlatform.as_ref().to_string());
2658 }
2659
2660 let url = params.parse_with_url(&url);
2661
2662 let mut json_mime_type = mime::APPLICATION_JSON;
2663 let mut request_value_reader = {
2664 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2665 common::remove_json_null_values(&mut value);
2666 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2667 serde_json::to_writer(&mut dst, &value).unwrap();
2668 dst
2669 };
2670 let request_size = request_value_reader
2671 .seek(std::io::SeekFrom::End(0))
2672 .unwrap();
2673 request_value_reader
2674 .seek(std::io::SeekFrom::Start(0))
2675 .unwrap();
2676
2677 loop {
2678 let token = match self
2679 .hub
2680 .auth
2681 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2682 .await
2683 {
2684 Ok(token) => token,
2685 Err(e) => match dlg.token(e) {
2686 Ok(token) => token,
2687 Err(e) => {
2688 dlg.finished(false);
2689 return Err(common::Error::MissingToken(e));
2690 }
2691 },
2692 };
2693 request_value_reader
2694 .seek(std::io::SeekFrom::Start(0))
2695 .unwrap();
2696 let mut req_result = {
2697 let client = &self.hub.client;
2698 dlg.pre_request();
2699 let mut req_builder = hyper::Request::builder()
2700 .method(hyper::Method::POST)
2701 .uri(url.as_str())
2702 .header(USER_AGENT, self.hub._user_agent.clone());
2703
2704 if let Some(token) = token.as_ref() {
2705 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2706 }
2707
2708 let request = req_builder
2709 .header(CONTENT_TYPE, json_mime_type.to_string())
2710 .header(CONTENT_LENGTH, request_size as u64)
2711 .body(common::to_body(
2712 request_value_reader.get_ref().clone().into(),
2713 ));
2714
2715 client.request(request.unwrap()).await
2716 };
2717
2718 match req_result {
2719 Err(err) => {
2720 if let common::Retry::After(d) = dlg.http_error(&err) {
2721 sleep(d).await;
2722 continue;
2723 }
2724 dlg.finished(false);
2725 return Err(common::Error::HttpError(err));
2726 }
2727 Ok(res) => {
2728 let (mut parts, body) = res.into_parts();
2729 let mut body = common::Body::new(body);
2730 if !parts.status.is_success() {
2731 let bytes = common::to_bytes(body).await.unwrap_or_default();
2732 let error = serde_json::from_str(&common::to_string(&bytes));
2733 let response = common::to_response(parts, bytes.into());
2734
2735 if let common::Retry::After(d) =
2736 dlg.http_failure(&response, error.as_ref().ok())
2737 {
2738 sleep(d).await;
2739 continue;
2740 }
2741
2742 dlg.finished(false);
2743
2744 return Err(match error {
2745 Ok(value) => common::Error::BadRequest(value),
2746 _ => common::Error::Failure(response),
2747 });
2748 }
2749 let response = {
2750 let bytes = common::to_bytes(body).await.unwrap_or_default();
2751 let encoded = common::to_string(&bytes);
2752 match serde_json::from_str(&encoded) {
2753 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2754 Err(error) => {
2755 dlg.response_json_decode_error(&encoded, &error);
2756 return Err(common::Error::JsonDecodeError(
2757 encoded.to_string(),
2758 error,
2759 ));
2760 }
2761 }
2762 };
2763
2764 dlg.finished(true);
2765 return Ok(response);
2766 }
2767 }
2768 }
2769 }
2770
2771 ///
2772 /// Sets the *request* property to the given value.
2773 ///
2774 /// Even though the property as already been set when instantiating this call,
2775 /// we provide this method for API completeness.
2776 pub fn request(mut self, new_value: ClassifyTextRequest) -> DocumentClassifyTextCall<'a, C> {
2777 self._request = new_value;
2778 self
2779 }
2780 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2781 /// while executing the actual API request.
2782 ///
2783 /// ````text
2784 /// It should be used to handle progress information, and to implement a certain level of resilience.
2785 /// ````
2786 ///
2787 /// Sets the *delegate* property to the given value.
2788 pub fn delegate(
2789 mut self,
2790 new_value: &'a mut dyn common::Delegate,
2791 ) -> DocumentClassifyTextCall<'a, C> {
2792 self._delegate = Some(new_value);
2793 self
2794 }
2795
2796 /// Set any additional parameter of the query string used in the request.
2797 /// It should be used to set parameters which are not yet available through their own
2798 /// setters.
2799 ///
2800 /// Please note that this method must not be used to set any of the known parameters
2801 /// which have their own setter method. If done anyway, the request will fail.
2802 ///
2803 /// # Additional Parameters
2804 ///
2805 /// * *$.xgafv* (query-string) - V1 error format.
2806 /// * *access_token* (query-string) - OAuth access token.
2807 /// * *alt* (query-string) - Data format for response.
2808 /// * *callback* (query-string) - JSONP
2809 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2810 /// * *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.
2811 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2812 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2813 /// * *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.
2814 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2815 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2816 pub fn param<T>(mut self, name: T, value: T) -> DocumentClassifyTextCall<'a, C>
2817 where
2818 T: AsRef<str>,
2819 {
2820 self._additional_params
2821 .insert(name.as_ref().to_string(), value.as_ref().to_string());
2822 self
2823 }
2824
2825 /// Identifies the authorization scope for the method you are building.
2826 ///
2827 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2828 /// [`Scope::CloudPlatform`].
2829 ///
2830 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2831 /// tokens for more than one scope.
2832 ///
2833 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2834 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2835 /// sufficient, a read-write scope will do as well.
2836 pub fn add_scope<St>(mut self, scope: St) -> DocumentClassifyTextCall<'a, C>
2837 where
2838 St: AsRef<str>,
2839 {
2840 self._scopes.insert(String::from(scope.as_ref()));
2841 self
2842 }
2843 /// Identifies the authorization scope(s) for the method you are building.
2844 ///
2845 /// See [`Self::add_scope()`] for details.
2846 pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentClassifyTextCall<'a, C>
2847 where
2848 I: IntoIterator<Item = St>,
2849 St: AsRef<str>,
2850 {
2851 self._scopes
2852 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2853 self
2854 }
2855
2856 /// Removes all scopes, and no default scope will be used either.
2857 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2858 /// for details).
2859 pub fn clear_scopes(mut self) -> DocumentClassifyTextCall<'a, C> {
2860 self._scopes.clear();
2861 self
2862 }
2863}
2864
2865/// Moderates a document for harmful and sensitive categories.
2866///
2867/// A builder for the *moderateText* method supported by a *document* resource.
2868/// It is not used directly, but through a [`DocumentMethods`] instance.
2869///
2870/// # Example
2871///
2872/// Instantiate a resource method builder
2873///
2874/// ```test_harness,no_run
2875/// # extern crate hyper;
2876/// # extern crate hyper_rustls;
2877/// # extern crate google_language1 as language1;
2878/// use language1::api::ModerateTextRequest;
2879/// # async fn dox() {
2880/// # use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2881///
2882/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2883/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2884/// # .with_native_roots()
2885/// # .unwrap()
2886/// # .https_only()
2887/// # .enable_http2()
2888/// # .build();
2889///
2890/// # let executor = hyper_util::rt::TokioExecutor::new();
2891/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2892/// # secret,
2893/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2894/// # yup_oauth2::client::CustomHyperClientBuilder::from(
2895/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
2896/// # ),
2897/// # ).build().await.unwrap();
2898///
2899/// # let client = hyper_util::client::legacy::Client::builder(
2900/// # hyper_util::rt::TokioExecutor::new()
2901/// # )
2902/// # .build(
2903/// # hyper_rustls::HttpsConnectorBuilder::new()
2904/// # .with_native_roots()
2905/// # .unwrap()
2906/// # .https_or_http()
2907/// # .enable_http2()
2908/// # .build()
2909/// # );
2910/// # let mut hub = CloudNaturalLanguage::new(client, auth);
2911/// // As the method needs a request, you would usually fill it with the desired information
2912/// // into the respective structure. Some of the parts shown here might not be applicable !
2913/// // Values shown here are possibly random and not representative !
2914/// let mut req = ModerateTextRequest::default();
2915///
2916/// // You can configure optional parameters by calling the respective setters at will, and
2917/// // execute the final call using `doit()`.
2918/// // Values shown here are possibly random and not representative !
2919/// let result = hub.documents().moderate_text(req)
2920/// .doit().await;
2921/// # }
2922/// ```
2923pub struct DocumentModerateTextCall<'a, C>
2924where
2925 C: 'a,
2926{
2927 hub: &'a CloudNaturalLanguage<C>,
2928 _request: ModerateTextRequest,
2929 _delegate: Option<&'a mut dyn common::Delegate>,
2930 _additional_params: HashMap<String, String>,
2931 _scopes: BTreeSet<String>,
2932}
2933
2934impl<'a, C> common::CallBuilder for DocumentModerateTextCall<'a, C> {}
2935
2936impl<'a, C> DocumentModerateTextCall<'a, C>
2937where
2938 C: common::Connector,
2939{
2940 /// Perform the operation you have build so far.
2941 pub async fn doit(mut self) -> common::Result<(common::Response, ModerateTextResponse)> {
2942 use std::borrow::Cow;
2943 use std::io::{Read, Seek};
2944
2945 use common::{url::Params, ToParts};
2946 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2947
2948 let mut dd = common::DefaultDelegate;
2949 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2950 dlg.begin(common::MethodInfo {
2951 id: "language.documents.moderateText",
2952 http_method: hyper::Method::POST,
2953 });
2954
2955 for &field in ["alt"].iter() {
2956 if self._additional_params.contains_key(field) {
2957 dlg.finished(false);
2958 return Err(common::Error::FieldClash(field));
2959 }
2960 }
2961
2962 let mut params = Params::with_capacity(3 + self._additional_params.len());
2963
2964 params.extend(self._additional_params.iter());
2965
2966 params.push("alt", "json");
2967 let mut url = self.hub._base_url.clone() + "v1/documents:moderateText";
2968 if self._scopes.is_empty() {
2969 self._scopes
2970 .insert(Scope::CloudPlatform.as_ref().to_string());
2971 }
2972
2973 let url = params.parse_with_url(&url);
2974
2975 let mut json_mime_type = mime::APPLICATION_JSON;
2976 let mut request_value_reader = {
2977 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2978 common::remove_json_null_values(&mut value);
2979 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2980 serde_json::to_writer(&mut dst, &value).unwrap();
2981 dst
2982 };
2983 let request_size = request_value_reader
2984 .seek(std::io::SeekFrom::End(0))
2985 .unwrap();
2986 request_value_reader
2987 .seek(std::io::SeekFrom::Start(0))
2988 .unwrap();
2989
2990 loop {
2991 let token = match self
2992 .hub
2993 .auth
2994 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2995 .await
2996 {
2997 Ok(token) => token,
2998 Err(e) => match dlg.token(e) {
2999 Ok(token) => token,
3000 Err(e) => {
3001 dlg.finished(false);
3002 return Err(common::Error::MissingToken(e));
3003 }
3004 },
3005 };
3006 request_value_reader
3007 .seek(std::io::SeekFrom::Start(0))
3008 .unwrap();
3009 let mut req_result = {
3010 let client = &self.hub.client;
3011 dlg.pre_request();
3012 let mut req_builder = hyper::Request::builder()
3013 .method(hyper::Method::POST)
3014 .uri(url.as_str())
3015 .header(USER_AGENT, self.hub._user_agent.clone());
3016
3017 if let Some(token) = token.as_ref() {
3018 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
3019 }
3020
3021 let request = req_builder
3022 .header(CONTENT_TYPE, json_mime_type.to_string())
3023 .header(CONTENT_LENGTH, request_size as u64)
3024 .body(common::to_body(
3025 request_value_reader.get_ref().clone().into(),
3026 ));
3027
3028 client.request(request.unwrap()).await
3029 };
3030
3031 match req_result {
3032 Err(err) => {
3033 if let common::Retry::After(d) = dlg.http_error(&err) {
3034 sleep(d).await;
3035 continue;
3036 }
3037 dlg.finished(false);
3038 return Err(common::Error::HttpError(err));
3039 }
3040 Ok(res) => {
3041 let (mut parts, body) = res.into_parts();
3042 let mut body = common::Body::new(body);
3043 if !parts.status.is_success() {
3044 let bytes = common::to_bytes(body).await.unwrap_or_default();
3045 let error = serde_json::from_str(&common::to_string(&bytes));
3046 let response = common::to_response(parts, bytes.into());
3047
3048 if let common::Retry::After(d) =
3049 dlg.http_failure(&response, error.as_ref().ok())
3050 {
3051 sleep(d).await;
3052 continue;
3053 }
3054
3055 dlg.finished(false);
3056
3057 return Err(match error {
3058 Ok(value) => common::Error::BadRequest(value),
3059 _ => common::Error::Failure(response),
3060 });
3061 }
3062 let response = {
3063 let bytes = common::to_bytes(body).await.unwrap_or_default();
3064 let encoded = common::to_string(&bytes);
3065 match serde_json::from_str(&encoded) {
3066 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
3067 Err(error) => {
3068 dlg.response_json_decode_error(&encoded, &error);
3069 return Err(common::Error::JsonDecodeError(
3070 encoded.to_string(),
3071 error,
3072 ));
3073 }
3074 }
3075 };
3076
3077 dlg.finished(true);
3078 return Ok(response);
3079 }
3080 }
3081 }
3082 }
3083
3084 ///
3085 /// Sets the *request* property to the given value.
3086 ///
3087 /// Even though the property as already been set when instantiating this call,
3088 /// we provide this method for API completeness.
3089 pub fn request(mut self, new_value: ModerateTextRequest) -> DocumentModerateTextCall<'a, C> {
3090 self._request = new_value;
3091 self
3092 }
3093 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
3094 /// while executing the actual API request.
3095 ///
3096 /// ````text
3097 /// It should be used to handle progress information, and to implement a certain level of resilience.
3098 /// ````
3099 ///
3100 /// Sets the *delegate* property to the given value.
3101 pub fn delegate(
3102 mut self,
3103 new_value: &'a mut dyn common::Delegate,
3104 ) -> DocumentModerateTextCall<'a, C> {
3105 self._delegate = Some(new_value);
3106 self
3107 }
3108
3109 /// Set any additional parameter of the query string used in the request.
3110 /// It should be used to set parameters which are not yet available through their own
3111 /// setters.
3112 ///
3113 /// Please note that this method must not be used to set any of the known parameters
3114 /// which have their own setter method. If done anyway, the request will fail.
3115 ///
3116 /// # Additional Parameters
3117 ///
3118 /// * *$.xgafv* (query-string) - V1 error format.
3119 /// * *access_token* (query-string) - OAuth access token.
3120 /// * *alt* (query-string) - Data format for response.
3121 /// * *callback* (query-string) - JSONP
3122 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
3123 /// * *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.
3124 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
3125 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
3126 /// * *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.
3127 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
3128 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
3129 pub fn param<T>(mut self, name: T, value: T) -> DocumentModerateTextCall<'a, C>
3130 where
3131 T: AsRef<str>,
3132 {
3133 self._additional_params
3134 .insert(name.as_ref().to_string(), value.as_ref().to_string());
3135 self
3136 }
3137
3138 /// Identifies the authorization scope for the method you are building.
3139 ///
3140 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
3141 /// [`Scope::CloudPlatform`].
3142 ///
3143 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
3144 /// tokens for more than one scope.
3145 ///
3146 /// Usually there is more than one suitable scope to authorize an operation, some of which may
3147 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
3148 /// sufficient, a read-write scope will do as well.
3149 pub fn add_scope<St>(mut self, scope: St) -> DocumentModerateTextCall<'a, C>
3150 where
3151 St: AsRef<str>,
3152 {
3153 self._scopes.insert(String::from(scope.as_ref()));
3154 self
3155 }
3156 /// Identifies the authorization scope(s) for the method you are building.
3157 ///
3158 /// See [`Self::add_scope()`] for details.
3159 pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentModerateTextCall<'a, C>
3160 where
3161 I: IntoIterator<Item = St>,
3162 St: AsRef<str>,
3163 {
3164 self._scopes
3165 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
3166 self
3167 }
3168
3169 /// Removes all scopes, and no default scope will be used either.
3170 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
3171 /// for details).
3172 pub fn clear_scopes(mut self) -> DocumentModerateTextCall<'a, C> {
3173 self._scopes.clear();
3174 self
3175 }
3176}