google_commentanalyzer1_alpha1/api.rs
1#![allow(clippy::ptr_arg)]
2
3use std::collections::{BTreeSet, HashMap};
4
5use tokio::time::sleep;
6
7// ##############
8// UTILITIES ###
9// ############
10
11/// Identifies the an OAuth2 authorization scope.
12/// A scope is needed when requesting an
13/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
14#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
15pub enum Scope {
16 /// View your email address
17 UserinfoEmail,
18}
19
20impl AsRef<str> for Scope {
21 fn as_ref(&self) -> &str {
22 match *self {
23 Scope::UserinfoEmail => "https://www.googleapis.com/auth/userinfo.email",
24 }
25 }
26}
27
28#[allow(clippy::derivable_impls)]
29impl Default for Scope {
30 fn default() -> Scope {
31 Scope::UserinfoEmail
32 }
33}
34
35// ########
36// HUB ###
37// ######
38
39/// Central instance to access all CommentAnalyzer related resource activities
40///
41/// # Examples
42///
43/// Instantiate a new hub
44///
45/// ```test_harness,no_run
46/// extern crate hyper;
47/// extern crate hyper_rustls;
48/// extern crate google_commentanalyzer1_alpha1 as commentanalyzer1_alpha1;
49/// use commentanalyzer1_alpha1::api::AnalyzeCommentRequest;
50/// use commentanalyzer1_alpha1::{Result, Error};
51/// # async fn dox() {
52/// use commentanalyzer1_alpha1::{CommentAnalyzer, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
53///
54/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
55/// // `client_secret`, among other things.
56/// let secret: yup_oauth2::ApplicationSecret = Default::default();
57/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
58/// // unless you replace `None` with the desired Flow.
59/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
60/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
61/// // retrieve them from storage.
62/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
63/// .with_native_roots()
64/// .unwrap()
65/// .https_only()
66/// .enable_http2()
67/// .build();
68///
69/// let executor = hyper_util::rt::TokioExecutor::new();
70/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
71/// secret,
72/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
73/// yup_oauth2::client::CustomHyperClientBuilder::from(
74/// hyper_util::client::legacy::Client::builder(executor).build(connector),
75/// ),
76/// ).build().await.unwrap();
77///
78/// let client = hyper_util::client::legacy::Client::builder(
79/// hyper_util::rt::TokioExecutor::new()
80/// )
81/// .build(
82/// hyper_rustls::HttpsConnectorBuilder::new()
83/// .with_native_roots()
84/// .unwrap()
85/// .https_or_http()
86/// .enable_http2()
87/// .build()
88/// );
89/// let mut hub = CommentAnalyzer::new(client, auth);
90/// // As the method needs a request, you would usually fill it with the desired information
91/// // into the respective structure. Some of the parts shown here might not be applicable !
92/// // Values shown here are possibly random and not representative !
93/// let mut req = AnalyzeCommentRequest::default();
94///
95/// // You can configure optional parameters by calling the respective setters at will, and
96/// // execute the final call using `doit()`.
97/// // Values shown here are possibly random and not representative !
98/// let result = hub.comments().analyze(req)
99/// .doit().await;
100///
101/// match result {
102/// Err(e) => match e {
103/// // The Error enum provides details about what exactly happened.
104/// // You can also just use its `Debug`, `Display` or `Error` traits
105/// Error::HttpError(_)
106/// |Error::Io(_)
107/// |Error::MissingAPIKey
108/// |Error::MissingToken(_)
109/// |Error::Cancelled
110/// |Error::UploadSizeLimitExceeded(_, _)
111/// |Error::Failure(_)
112/// |Error::BadRequest(_)
113/// |Error::FieldClash(_)
114/// |Error::JsonDecodeError(_, _) => println!("{}", e),
115/// },
116/// Ok(res) => println!("Success: {:?}", res),
117/// }
118/// # }
119/// ```
120#[derive(Clone)]
121pub struct CommentAnalyzer<C> {
122 pub client: common::Client<C>,
123 pub auth: Box<dyn common::GetToken>,
124 _user_agent: String,
125 _base_url: String,
126 _root_url: String,
127}
128
129impl<C> common::Hub for CommentAnalyzer<C> {}
130
131impl<'a, C> CommentAnalyzer<C> {
132 pub fn new<A: 'static + common::GetToken>(
133 client: common::Client<C>,
134 auth: A,
135 ) -> CommentAnalyzer<C> {
136 CommentAnalyzer {
137 client,
138 auth: Box::new(auth),
139 _user_agent: "google-api-rust-client/7.0.0".to_string(),
140 _base_url: "https://commentanalyzer.googleapis.com/".to_string(),
141 _root_url: "https://commentanalyzer.googleapis.com/".to_string(),
142 }
143 }
144
145 pub fn comments(&'a self) -> CommentMethods<'a, C> {
146 CommentMethods { hub: self }
147 }
148
149 /// Set the user-agent header field to use in all requests to the server.
150 /// It defaults to `google-api-rust-client/7.0.0`.
151 ///
152 /// Returns the previously set user-agent.
153 pub fn user_agent(&mut self, agent_name: String) -> String {
154 std::mem::replace(&mut self._user_agent, agent_name)
155 }
156
157 /// Set the base url to use in all requests to the server.
158 /// It defaults to `https://commentanalyzer.googleapis.com/`.
159 ///
160 /// Returns the previously set base url.
161 pub fn base_url(&mut self, new_base_url: String) -> String {
162 std::mem::replace(&mut self._base_url, new_base_url)
163 }
164
165 /// Set the root url to use in all requests to the server.
166 /// It defaults to `https://commentanalyzer.googleapis.com/`.
167 ///
168 /// Returns the previously set root url.
169 pub fn root_url(&mut self, new_root_url: String) -> String {
170 std::mem::replace(&mut self._root_url, new_root_url)
171 }
172}
173
174// ############
175// SCHEMAS ###
176// ##########
177/// The comment analysis request message.
178/// LINT.IfChange
179///
180/// # Activities
181///
182/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
183/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
184///
185/// * [analyze comments](CommentAnalyzeCall) (request)
186#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
187#[serde_with::serde_as]
188#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
189pub struct AnalyzeCommentRequest {
190 /// Opaque token that is echoed from the request to the response.
191 #[serde(rename = "clientToken")]
192 pub client_token: Option<String>,
193 /// The comment to analyze.
194 pub comment: Option<TextEntry>,
195 /// Optional identifier associating this AnalyzeCommentRequest with a
196 /// particular client's community. Different communities may have different
197 /// norms and rules. Specifying this value enables us to explore building
198 /// community-specific models for clients.
199 #[serde(rename = "communityId")]
200 pub community_id: Option<String>,
201 /// The context of the comment.
202 pub context: Option<Context>,
203 /// Do not store the comment or context sent in this request. By default, the
204 /// service may store comments/context for debugging purposes.
205 #[serde(rename = "doNotStore")]
206 pub do_not_store: Option<bool>,
207 /// The language(s) of the comment and context. If none are specified, we
208 /// attempt to automatically detect the language. Specifying multiple languages
209 /// means the text contains multiple lanugages. Both ISO and BCP-47 language
210 /// codes are accepted.
211 ///
212 /// The server returns an error if no language was specified and language
213 /// detection fails. The server also returns an error if the languages (either
214 /// specified by the caller, or auto-detected) are not *all* supported by the
215 /// service.
216 pub languages: Option<Vec<String>>,
217 /// Specification of requested attributes. The AttributeParameters serve as
218 /// configuration for each associated attribute. The map keys are attribute
219 /// names. The available attributes may be different on each RFE installation,
220 /// and can be seen by calling ListAttributes (see above).
221 /// For the prod installation, known as Perspective API, at
222 /// blade:commentanalyzer-esf and commentanalyzer.googleapis.com, see
223 /// go/checker-models (internal) and
224 /// https://github.com/conversationai/perspectiveapi/blob/master/2-api/models.md#all-attribute-types.
225 #[serde(rename = "requestedAttributes")]
226 pub requested_attributes: Option<HashMap<String, AttributeParameters>>,
227 /// Session ID. Used to join related RPCs into a single session. For example,
228 /// an interactive tool that calls both the AnalyzeComment and
229 /// SuggestCommentScore RPCs should set all invocations of both RPCs to the
230 /// same Session ID, typically a random 64-bit integer.
231 #[serde(rename = "sessionId")]
232 pub session_id: Option<String>,
233 /// An advisory parameter that will return span annotations if the model
234 /// is capable of providing scores with sub-comment resolution. This will
235 /// likely increase the size of the returned message.
236 #[serde(rename = "spanAnnotations")]
237 pub span_annotations: Option<bool>,
238}
239
240impl common::RequestValue for AnalyzeCommentRequest {}
241
242/// The comment analysis response message.
243///
244/// # Activities
245///
246/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
247/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
248///
249/// * [analyze comments](CommentAnalyzeCall) (response)
250#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
251#[serde_with::serde_as]
252#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
253pub struct AnalyzeCommentResponse {
254 /// Scores for the requested attributes. The map keys are attribute names (same
255 /// as the requested_attribute field in AnalyzeCommentRequest, for example
256 /// "ATTACK_ON_AUTHOR", "INFLAMMATORY", etc).
257 #[serde(rename = "attributeScores")]
258 pub attribute_scores: Option<HashMap<String, AttributeScores>>,
259 /// Same token from the original AnalyzeCommentRequest.
260 #[serde(rename = "clientToken")]
261 pub client_token: Option<String>,
262 /// Contains the languages detected from the text content, sorted in order of
263 /// likelihood.
264 #[serde(rename = "detectedLanguages")]
265 pub detected_languages: Option<Vec<String>>,
266 /// The language(s) used by CommentAnalyzer service to choose which Model to
267 /// use when analyzing the comment. Might better be called
268 /// “effective_languages”. The logic used to make the choice is as follows:
269 /// if !Request.languages.empty()
270 /// effective_languages = Request.languages
271 /// else
272 /// effective_languages = detected_languages\[0\]
273 pub languages: Option<Vec<String>>,
274}
275
276impl common::ResponseResult for AnalyzeCommentResponse {}
277
278/// A type of context specific to a comment left on a single-threaded comment
279/// message board, where comments are either a top level comment or the child of
280/// a top level comment.
281///
282/// This type is not used in any activity, and only used as *part* of another schema.
283///
284#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
285#[serde_with::serde_as]
286#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
287pub struct ArticleAndParentComment {
288 /// The source content about which the comment was made (article text, article
289 /// summary, video transcript, etc).
290 pub article: Option<TextEntry>,
291 /// Refers to text that is a direct parent of the source comment, such as in a
292 /// one-deep threaded message board. This field will only be present for
293 /// comments that are replies to other comments and will not be populated for
294 /// direct comments on the article_text.
295 #[serde(rename = "parentComment")]
296 pub parent_comment: Option<TextEntry>,
297}
298
299impl common::Part for ArticleAndParentComment {}
300
301/// Configurable parameters for attribute scoring.
302///
303/// This type is not used in any activity, and only used as *part* of another schema.
304///
305#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
306#[serde_with::serde_as]
307#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
308pub struct AttributeParameters {
309 /// Don't return scores for this attribute that are below this threshold. If
310 /// unset, a default threshold will be applied. A FloatValue wrapper is used to
311 /// distinguish between 0 vs. default/unset.
312 #[serde(rename = "scoreThreshold")]
313 pub score_threshold: Option<f32>,
314 /// What type of scores to return. If unset, defaults to probability scores.
315 #[serde(rename = "scoreType")]
316 pub score_type: Option<String>,
317}
318
319impl common::Part for AttributeParameters {}
320
321/// This holds score values for a single attribute. It contains both per-span
322/// scores as well as an overall summary score..
323///
324/// This type is not used in any activity, and only used as *part* of another schema.
325///
326#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
327#[serde_with::serde_as]
328#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
329pub struct AttributeScores {
330 /// Per-span scores.
331 #[serde(rename = "spanScores")]
332 pub span_scores: Option<Vec<SpanScore>>,
333 /// Overall score for comment as a whole.
334 #[serde(rename = "summaryScore")]
335 pub summary_score: Option<Score>,
336}
337
338impl common::Part for AttributeScores {}
339
340/// Context is typically something that a Comment is referencing or replying to
341/// (such as an article, or previous comment).
342/// Note: Populate only ONE OF the following fields. The oneof syntax cannot be
343/// used because that would require nesting entries inside another message and
344/// breaking backwards compatibility. The server will return an error if more
345/// than one of the following fields is present.
346///
347/// This type is not used in any activity, and only used as *part* of another schema.
348///
349#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
350#[serde_with::serde_as]
351#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
352pub struct Context {
353 /// Information about the source for which the original comment was made, and
354 /// any parent comment info.
355 #[serde(rename = "articleAndParentComment")]
356 pub article_and_parent_comment: Option<ArticleAndParentComment>,
357 /// A list of messages. For example, a linear comments section or forum thread.
358 pub entries: Option<Vec<TextEntry>>,
359}
360
361impl common::Part for Context {}
362
363/// Analysis scores are described by a value and a ScoreType.
364///
365/// This type is not used in any activity, and only used as *part* of another schema.
366///
367#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
368#[serde_with::serde_as]
369#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
370pub struct Score {
371 /// The type of the above value.
372 #[serde(rename = "type")]
373 pub type_: Option<String>,
374 /// Score value. Semantics described by type below.
375 pub value: Option<f32>,
376}
377
378impl common::Part for Score {}
379
380/// This is a single score for a given span of text.
381///
382/// This type is not used in any activity, and only used as *part* of another schema.
383///
384#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
385#[serde_with::serde_as]
386#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
387pub struct SpanScore {
388 /// "begin" and "end" describe the span of the original text that the attribute
389 /// score applies to. The values are the UTF-16 codepoint range. "end" is
390 /// exclusive. For example, with the text "Hi there", the begin/end pair (0,2)
391 /// describes the text "Hi".
392 ///
393 /// If "begin" and "end" are unset, the score applies to the full text.
394 pub begin: Option<i32>,
395 /// no description provided
396 pub end: Option<i32>,
397 /// The score value.
398 pub score: Option<Score>,
399}
400
401impl common::Part for SpanScore {}
402
403/// The comment score suggestion request message.
404///
405/// # Activities
406///
407/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
408/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
409///
410/// * [suggestscore comments](CommentSuggestscoreCall) (request)
411#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
412#[serde_with::serde_as]
413#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
414pub struct SuggestCommentScoreRequest {
415 /// Attribute scores for the comment. The map keys are attribute names, same as
416 /// the requested_attribute field in AnalyzeCommentRequest (for example
417 /// "ATTACK_ON_AUTHOR", "INFLAMMATORY", etc.). This field has the same type as
418 /// the `attribute_scores` field in AnalyzeCommentResponse.
419 ///
420 /// To specify an overall attribute score for the entire comment as a whole,
421 /// use the `summary_score` field of the mapped AttributeScores object. To
422 /// specify scores on specific subparts of the comment, use the `span_scores`
423 /// field. All SpanScore objects must have begin and end fields set.
424 ///
425 /// All Score objects must be explicitly set (for binary classification, use
426 /// the score values 0 and 1). If Score objects don't include a ScoreType,
427 /// `PROBABILITY` is assumed.
428 ///
429 /// `attribute_scores` must not be empty. The mapped AttributeScores objects
430 /// also must not be empty. An `INVALID_ARGUMENT` error is returned for all
431 /// malformed requests.
432 #[serde(rename = "attributeScores")]
433 pub attribute_scores: Option<HashMap<String, AttributeScores>>,
434 /// Opaque token that is echoed from the request to the response.
435 #[serde(rename = "clientToken")]
436 pub client_token: Option<String>,
437 /// The comment being scored.
438 pub comment: Option<TextEntry>,
439 /// Optional identifier associating this comment score suggestion with a
440 /// particular sub-community. Different communities may have different norms
441 /// and rules. Specifying this value enables training community-specific
442 /// models.
443 #[serde(rename = "communityId")]
444 pub community_id: Option<String>,
445 /// The context of the comment.
446 pub context: Option<Context>,
447 /// The language(s) of the comment and context. If none are specified, we
448 /// attempt to automatically detect the language. Both ISO and BCP-47 language
449 /// codes are accepted.
450 pub languages: Option<Vec<String>>,
451 /// Session ID. Used to join related RPCs into a single session. For example,
452 /// an interactive tool that calls both the AnalyzeComment and
453 /// SuggestCommentScore RPCs should set all invocations of both RPCs to the
454 /// same Session ID, typically a random 64-bit integer.
455 #[serde(rename = "sessionId")]
456 pub session_id: Option<String>,
457}
458
459impl common::RequestValue for SuggestCommentScoreRequest {}
460
461/// The comment score suggestion response message.
462///
463/// # Activities
464///
465/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
466/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
467///
468/// * [suggestscore comments](CommentSuggestscoreCall) (response)
469#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
470#[serde_with::serde_as]
471#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
472pub struct SuggestCommentScoreResponse {
473 /// Same token from the original SuggestCommentScoreRequest.
474 #[serde(rename = "clientToken")]
475 pub client_token: Option<String>,
476 /// The list of languages detected from the comment text.
477 #[serde(rename = "detectedLanguages")]
478 pub detected_languages: Option<Vec<String>>,
479 /// The list of languages provided in the request.
480 #[serde(rename = "requestedLanguages")]
481 pub requested_languages: Option<Vec<String>>,
482}
483
484impl common::ResponseResult for SuggestCommentScoreResponse {}
485
486/// Represents a body of text.
487///
488/// This type is not used in any activity, and only used as *part* of another schema.
489///
490#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
491#[serde_with::serde_as]
492#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
493pub struct TextEntry {
494 /// UTF-8 encoded text.
495 pub text: Option<String>,
496 /// Type of the text field.
497 #[serde(rename = "type")]
498 pub type_: Option<String>,
499}
500
501impl common::Part for TextEntry {}
502
503// ###################
504// MethodBuilders ###
505// #################
506
507/// A builder providing access to all methods supported on *comment* resources.
508/// It is not used directly, but through the [`CommentAnalyzer`] hub.
509///
510/// # Example
511///
512/// Instantiate a resource builder
513///
514/// ```test_harness,no_run
515/// extern crate hyper;
516/// extern crate hyper_rustls;
517/// extern crate google_commentanalyzer1_alpha1 as commentanalyzer1_alpha1;
518///
519/// # async fn dox() {
520/// use commentanalyzer1_alpha1::{CommentAnalyzer, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
521///
522/// let secret: yup_oauth2::ApplicationSecret = Default::default();
523/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
524/// .with_native_roots()
525/// .unwrap()
526/// .https_only()
527/// .enable_http2()
528/// .build();
529///
530/// let executor = hyper_util::rt::TokioExecutor::new();
531/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
532/// secret,
533/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
534/// yup_oauth2::client::CustomHyperClientBuilder::from(
535/// hyper_util::client::legacy::Client::builder(executor).build(connector),
536/// ),
537/// ).build().await.unwrap();
538///
539/// let client = hyper_util::client::legacy::Client::builder(
540/// hyper_util::rt::TokioExecutor::new()
541/// )
542/// .build(
543/// hyper_rustls::HttpsConnectorBuilder::new()
544/// .with_native_roots()
545/// .unwrap()
546/// .https_or_http()
547/// .enable_http2()
548/// .build()
549/// );
550/// let mut hub = CommentAnalyzer::new(client, auth);
551/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
552/// // like `analyze(...)` and `suggestscore(...)`
553/// // to build up your call.
554/// let rb = hub.comments();
555/// # }
556/// ```
557pub struct CommentMethods<'a, C>
558where
559 C: 'a,
560{
561 hub: &'a CommentAnalyzer<C>,
562}
563
564impl<'a, C> common::MethodsBuilder for CommentMethods<'a, C> {}
565
566impl<'a, C> CommentMethods<'a, C> {
567 /// Create a builder to help you perform the following task:
568 ///
569 /// Analyzes the provided text and returns scores for requested attributes.
570 ///
571 /// # Arguments
572 ///
573 /// * `request` - No description provided.
574 pub fn analyze(&self, request: AnalyzeCommentRequest) -> CommentAnalyzeCall<'a, C> {
575 CommentAnalyzeCall {
576 hub: self.hub,
577 _request: request,
578 _delegate: Default::default(),
579 _additional_params: Default::default(),
580 _scopes: Default::default(),
581 }
582 }
583
584 /// Create a builder to help you perform the following task:
585 ///
586 /// Suggest comment scores as training data.
587 ///
588 /// # Arguments
589 ///
590 /// * `request` - No description provided.
591 pub fn suggestscore(
592 &self,
593 request: SuggestCommentScoreRequest,
594 ) -> CommentSuggestscoreCall<'a, C> {
595 CommentSuggestscoreCall {
596 hub: self.hub,
597 _request: request,
598 _delegate: Default::default(),
599 _additional_params: Default::default(),
600 _scopes: Default::default(),
601 }
602 }
603}
604
605// ###################
606// CallBuilders ###
607// #################
608
609/// Analyzes the provided text and returns scores for requested attributes.
610///
611/// A builder for the *analyze* method supported by a *comment* resource.
612/// It is not used directly, but through a [`CommentMethods`] instance.
613///
614/// # Example
615///
616/// Instantiate a resource method builder
617///
618/// ```test_harness,no_run
619/// # extern crate hyper;
620/// # extern crate hyper_rustls;
621/// # extern crate google_commentanalyzer1_alpha1 as commentanalyzer1_alpha1;
622/// use commentanalyzer1_alpha1::api::AnalyzeCommentRequest;
623/// # async fn dox() {
624/// # use commentanalyzer1_alpha1::{CommentAnalyzer, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
625///
626/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
627/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
628/// # .with_native_roots()
629/// # .unwrap()
630/// # .https_only()
631/// # .enable_http2()
632/// # .build();
633///
634/// # let executor = hyper_util::rt::TokioExecutor::new();
635/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
636/// # secret,
637/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
638/// # yup_oauth2::client::CustomHyperClientBuilder::from(
639/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
640/// # ),
641/// # ).build().await.unwrap();
642///
643/// # let client = hyper_util::client::legacy::Client::builder(
644/// # hyper_util::rt::TokioExecutor::new()
645/// # )
646/// # .build(
647/// # hyper_rustls::HttpsConnectorBuilder::new()
648/// # .with_native_roots()
649/// # .unwrap()
650/// # .https_or_http()
651/// # .enable_http2()
652/// # .build()
653/// # );
654/// # let mut hub = CommentAnalyzer::new(client, auth);
655/// // As the method needs a request, you would usually fill it with the desired information
656/// // into the respective structure. Some of the parts shown here might not be applicable !
657/// // Values shown here are possibly random and not representative !
658/// let mut req = AnalyzeCommentRequest::default();
659///
660/// // You can configure optional parameters by calling the respective setters at will, and
661/// // execute the final call using `doit()`.
662/// // Values shown here are possibly random and not representative !
663/// let result = hub.comments().analyze(req)
664/// .doit().await;
665/// # }
666/// ```
667pub struct CommentAnalyzeCall<'a, C>
668where
669 C: 'a,
670{
671 hub: &'a CommentAnalyzer<C>,
672 _request: AnalyzeCommentRequest,
673 _delegate: Option<&'a mut dyn common::Delegate>,
674 _additional_params: HashMap<String, String>,
675 _scopes: BTreeSet<String>,
676}
677
678impl<'a, C> common::CallBuilder for CommentAnalyzeCall<'a, C> {}
679
680impl<'a, C> CommentAnalyzeCall<'a, C>
681where
682 C: common::Connector,
683{
684 /// Perform the operation you have build so far.
685 pub async fn doit(mut self) -> common::Result<(common::Response, AnalyzeCommentResponse)> {
686 use std::borrow::Cow;
687 use std::io::{Read, Seek};
688
689 use common::{url::Params, ToParts};
690 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
691
692 let mut dd = common::DefaultDelegate;
693 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
694 dlg.begin(common::MethodInfo {
695 id: "commentanalyzer.comments.analyze",
696 http_method: hyper::Method::POST,
697 });
698
699 for &field in ["alt"].iter() {
700 if self._additional_params.contains_key(field) {
701 dlg.finished(false);
702 return Err(common::Error::FieldClash(field));
703 }
704 }
705
706 let mut params = Params::with_capacity(3 + self._additional_params.len());
707
708 params.extend(self._additional_params.iter());
709
710 params.push("alt", "json");
711 let mut url = self.hub._base_url.clone() + "v1alpha1/comments:analyze";
712 if self._scopes.is_empty() {
713 self._scopes
714 .insert(Scope::UserinfoEmail.as_ref().to_string());
715 }
716
717 let url = params.parse_with_url(&url);
718
719 let mut json_mime_type = mime::APPLICATION_JSON;
720 let mut request_value_reader = {
721 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
722 common::remove_json_null_values(&mut value);
723 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
724 serde_json::to_writer(&mut dst, &value).unwrap();
725 dst
726 };
727 let request_size = request_value_reader
728 .seek(std::io::SeekFrom::End(0))
729 .unwrap();
730 request_value_reader
731 .seek(std::io::SeekFrom::Start(0))
732 .unwrap();
733
734 loop {
735 let token = match self
736 .hub
737 .auth
738 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
739 .await
740 {
741 Ok(token) => token,
742 Err(e) => match dlg.token(e) {
743 Ok(token) => token,
744 Err(e) => {
745 dlg.finished(false);
746 return Err(common::Error::MissingToken(e));
747 }
748 },
749 };
750 request_value_reader
751 .seek(std::io::SeekFrom::Start(0))
752 .unwrap();
753 let mut req_result = {
754 let client = &self.hub.client;
755 dlg.pre_request();
756 let mut req_builder = hyper::Request::builder()
757 .method(hyper::Method::POST)
758 .uri(url.as_str())
759 .header(USER_AGENT, self.hub._user_agent.clone());
760
761 if let Some(token) = token.as_ref() {
762 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
763 }
764
765 let request = req_builder
766 .header(CONTENT_TYPE, json_mime_type.to_string())
767 .header(CONTENT_LENGTH, request_size as u64)
768 .body(common::to_body(
769 request_value_reader.get_ref().clone().into(),
770 ));
771
772 client.request(request.unwrap()).await
773 };
774
775 match req_result {
776 Err(err) => {
777 if let common::Retry::After(d) = dlg.http_error(&err) {
778 sleep(d).await;
779 continue;
780 }
781 dlg.finished(false);
782 return Err(common::Error::HttpError(err));
783 }
784 Ok(res) => {
785 let (mut parts, body) = res.into_parts();
786 let mut body = common::Body::new(body);
787 if !parts.status.is_success() {
788 let bytes = common::to_bytes(body).await.unwrap_or_default();
789 let error = serde_json::from_str(&common::to_string(&bytes));
790 let response = common::to_response(parts, bytes.into());
791
792 if let common::Retry::After(d) =
793 dlg.http_failure(&response, error.as_ref().ok())
794 {
795 sleep(d).await;
796 continue;
797 }
798
799 dlg.finished(false);
800
801 return Err(match error {
802 Ok(value) => common::Error::BadRequest(value),
803 _ => common::Error::Failure(response),
804 });
805 }
806 let response = {
807 let bytes = common::to_bytes(body).await.unwrap_or_default();
808 let encoded = common::to_string(&bytes);
809 match serde_json::from_str(&encoded) {
810 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
811 Err(error) => {
812 dlg.response_json_decode_error(&encoded, &error);
813 return Err(common::Error::JsonDecodeError(
814 encoded.to_string(),
815 error,
816 ));
817 }
818 }
819 };
820
821 dlg.finished(true);
822 return Ok(response);
823 }
824 }
825 }
826 }
827
828 ///
829 /// Sets the *request* property to the given value.
830 ///
831 /// Even though the property as already been set when instantiating this call,
832 /// we provide this method for API completeness.
833 pub fn request(mut self, new_value: AnalyzeCommentRequest) -> CommentAnalyzeCall<'a, C> {
834 self._request = new_value;
835 self
836 }
837 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
838 /// while executing the actual API request.
839 ///
840 /// ````text
841 /// It should be used to handle progress information, and to implement a certain level of resilience.
842 /// ````
843 ///
844 /// Sets the *delegate* property to the given value.
845 pub fn delegate(
846 mut self,
847 new_value: &'a mut dyn common::Delegate,
848 ) -> CommentAnalyzeCall<'a, C> {
849 self._delegate = Some(new_value);
850 self
851 }
852
853 /// Set any additional parameter of the query string used in the request.
854 /// It should be used to set parameters which are not yet available through their own
855 /// setters.
856 ///
857 /// Please note that this method must not be used to set any of the known parameters
858 /// which have their own setter method. If done anyway, the request will fail.
859 ///
860 /// # Additional Parameters
861 ///
862 /// * *$.xgafv* (query-string) - V1 error format.
863 /// * *access_token* (query-string) - OAuth access token.
864 /// * *alt* (query-string) - Data format for response.
865 /// * *callback* (query-string) - JSONP
866 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
867 /// * *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.
868 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
869 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
870 /// * *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.
871 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
872 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
873 pub fn param<T>(mut self, name: T, value: T) -> CommentAnalyzeCall<'a, C>
874 where
875 T: AsRef<str>,
876 {
877 self._additional_params
878 .insert(name.as_ref().to_string(), value.as_ref().to_string());
879 self
880 }
881
882 /// Identifies the authorization scope for the method you are building.
883 ///
884 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
885 /// [`Scope::UserinfoEmail`].
886 ///
887 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
888 /// tokens for more than one scope.
889 ///
890 /// Usually there is more than one suitable scope to authorize an operation, some of which may
891 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
892 /// sufficient, a read-write scope will do as well.
893 pub fn add_scope<St>(mut self, scope: St) -> CommentAnalyzeCall<'a, C>
894 where
895 St: AsRef<str>,
896 {
897 self._scopes.insert(String::from(scope.as_ref()));
898 self
899 }
900 /// Identifies the authorization scope(s) for the method you are building.
901 ///
902 /// See [`Self::add_scope()`] for details.
903 pub fn add_scopes<I, St>(mut self, scopes: I) -> CommentAnalyzeCall<'a, C>
904 where
905 I: IntoIterator<Item = St>,
906 St: AsRef<str>,
907 {
908 self._scopes
909 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
910 self
911 }
912
913 /// Removes all scopes, and no default scope will be used either.
914 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
915 /// for details).
916 pub fn clear_scopes(mut self) -> CommentAnalyzeCall<'a, C> {
917 self._scopes.clear();
918 self
919 }
920}
921
922/// Suggest comment scores as training data.
923///
924/// A builder for the *suggestscore* method supported by a *comment* resource.
925/// It is not used directly, but through a [`CommentMethods`] instance.
926///
927/// # Example
928///
929/// Instantiate a resource method builder
930///
931/// ```test_harness,no_run
932/// # extern crate hyper;
933/// # extern crate hyper_rustls;
934/// # extern crate google_commentanalyzer1_alpha1 as commentanalyzer1_alpha1;
935/// use commentanalyzer1_alpha1::api::SuggestCommentScoreRequest;
936/// # async fn dox() {
937/// # use commentanalyzer1_alpha1::{CommentAnalyzer, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
938///
939/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
940/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
941/// # .with_native_roots()
942/// # .unwrap()
943/// # .https_only()
944/// # .enable_http2()
945/// # .build();
946///
947/// # let executor = hyper_util::rt::TokioExecutor::new();
948/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
949/// # secret,
950/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
951/// # yup_oauth2::client::CustomHyperClientBuilder::from(
952/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
953/// # ),
954/// # ).build().await.unwrap();
955///
956/// # let client = hyper_util::client::legacy::Client::builder(
957/// # hyper_util::rt::TokioExecutor::new()
958/// # )
959/// # .build(
960/// # hyper_rustls::HttpsConnectorBuilder::new()
961/// # .with_native_roots()
962/// # .unwrap()
963/// # .https_or_http()
964/// # .enable_http2()
965/// # .build()
966/// # );
967/// # let mut hub = CommentAnalyzer::new(client, auth);
968/// // As the method needs a request, you would usually fill it with the desired information
969/// // into the respective structure. Some of the parts shown here might not be applicable !
970/// // Values shown here are possibly random and not representative !
971/// let mut req = SuggestCommentScoreRequest::default();
972///
973/// // You can configure optional parameters by calling the respective setters at will, and
974/// // execute the final call using `doit()`.
975/// // Values shown here are possibly random and not representative !
976/// let result = hub.comments().suggestscore(req)
977/// .doit().await;
978/// # }
979/// ```
980pub struct CommentSuggestscoreCall<'a, C>
981where
982 C: 'a,
983{
984 hub: &'a CommentAnalyzer<C>,
985 _request: SuggestCommentScoreRequest,
986 _delegate: Option<&'a mut dyn common::Delegate>,
987 _additional_params: HashMap<String, String>,
988 _scopes: BTreeSet<String>,
989}
990
991impl<'a, C> common::CallBuilder for CommentSuggestscoreCall<'a, C> {}
992
993impl<'a, C> CommentSuggestscoreCall<'a, C>
994where
995 C: common::Connector,
996{
997 /// Perform the operation you have build so far.
998 pub async fn doit(mut self) -> common::Result<(common::Response, SuggestCommentScoreResponse)> {
999 use std::borrow::Cow;
1000 use std::io::{Read, Seek};
1001
1002 use common::{url::Params, ToParts};
1003 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1004
1005 let mut dd = common::DefaultDelegate;
1006 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1007 dlg.begin(common::MethodInfo {
1008 id: "commentanalyzer.comments.suggestscore",
1009 http_method: hyper::Method::POST,
1010 });
1011
1012 for &field in ["alt"].iter() {
1013 if self._additional_params.contains_key(field) {
1014 dlg.finished(false);
1015 return Err(common::Error::FieldClash(field));
1016 }
1017 }
1018
1019 let mut params = Params::with_capacity(3 + self._additional_params.len());
1020
1021 params.extend(self._additional_params.iter());
1022
1023 params.push("alt", "json");
1024 let mut url = self.hub._base_url.clone() + "v1alpha1/comments:suggestscore";
1025 if self._scopes.is_empty() {
1026 self._scopes
1027 .insert(Scope::UserinfoEmail.as_ref().to_string());
1028 }
1029
1030 let url = params.parse_with_url(&url);
1031
1032 let mut json_mime_type = mime::APPLICATION_JSON;
1033 let mut request_value_reader = {
1034 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1035 common::remove_json_null_values(&mut value);
1036 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1037 serde_json::to_writer(&mut dst, &value).unwrap();
1038 dst
1039 };
1040 let request_size = request_value_reader
1041 .seek(std::io::SeekFrom::End(0))
1042 .unwrap();
1043 request_value_reader
1044 .seek(std::io::SeekFrom::Start(0))
1045 .unwrap();
1046
1047 loop {
1048 let token = match self
1049 .hub
1050 .auth
1051 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1052 .await
1053 {
1054 Ok(token) => token,
1055 Err(e) => match dlg.token(e) {
1056 Ok(token) => token,
1057 Err(e) => {
1058 dlg.finished(false);
1059 return Err(common::Error::MissingToken(e));
1060 }
1061 },
1062 };
1063 request_value_reader
1064 .seek(std::io::SeekFrom::Start(0))
1065 .unwrap();
1066 let mut req_result = {
1067 let client = &self.hub.client;
1068 dlg.pre_request();
1069 let mut req_builder = hyper::Request::builder()
1070 .method(hyper::Method::POST)
1071 .uri(url.as_str())
1072 .header(USER_AGENT, self.hub._user_agent.clone());
1073
1074 if let Some(token) = token.as_ref() {
1075 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1076 }
1077
1078 let request = req_builder
1079 .header(CONTENT_TYPE, json_mime_type.to_string())
1080 .header(CONTENT_LENGTH, request_size as u64)
1081 .body(common::to_body(
1082 request_value_reader.get_ref().clone().into(),
1083 ));
1084
1085 client.request(request.unwrap()).await
1086 };
1087
1088 match req_result {
1089 Err(err) => {
1090 if let common::Retry::After(d) = dlg.http_error(&err) {
1091 sleep(d).await;
1092 continue;
1093 }
1094 dlg.finished(false);
1095 return Err(common::Error::HttpError(err));
1096 }
1097 Ok(res) => {
1098 let (mut parts, body) = res.into_parts();
1099 let mut body = common::Body::new(body);
1100 if !parts.status.is_success() {
1101 let bytes = common::to_bytes(body).await.unwrap_or_default();
1102 let error = serde_json::from_str(&common::to_string(&bytes));
1103 let response = common::to_response(parts, bytes.into());
1104
1105 if let common::Retry::After(d) =
1106 dlg.http_failure(&response, error.as_ref().ok())
1107 {
1108 sleep(d).await;
1109 continue;
1110 }
1111
1112 dlg.finished(false);
1113
1114 return Err(match error {
1115 Ok(value) => common::Error::BadRequest(value),
1116 _ => common::Error::Failure(response),
1117 });
1118 }
1119 let response = {
1120 let bytes = common::to_bytes(body).await.unwrap_or_default();
1121 let encoded = common::to_string(&bytes);
1122 match serde_json::from_str(&encoded) {
1123 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1124 Err(error) => {
1125 dlg.response_json_decode_error(&encoded, &error);
1126 return Err(common::Error::JsonDecodeError(
1127 encoded.to_string(),
1128 error,
1129 ));
1130 }
1131 }
1132 };
1133
1134 dlg.finished(true);
1135 return Ok(response);
1136 }
1137 }
1138 }
1139 }
1140
1141 ///
1142 /// Sets the *request* property to the given value.
1143 ///
1144 /// Even though the property as already been set when instantiating this call,
1145 /// we provide this method for API completeness.
1146 pub fn request(
1147 mut self,
1148 new_value: SuggestCommentScoreRequest,
1149 ) -> CommentSuggestscoreCall<'a, C> {
1150 self._request = new_value;
1151 self
1152 }
1153 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1154 /// while executing the actual API request.
1155 ///
1156 /// ````text
1157 /// It should be used to handle progress information, and to implement a certain level of resilience.
1158 /// ````
1159 ///
1160 /// Sets the *delegate* property to the given value.
1161 pub fn delegate(
1162 mut self,
1163 new_value: &'a mut dyn common::Delegate,
1164 ) -> CommentSuggestscoreCall<'a, C> {
1165 self._delegate = Some(new_value);
1166 self
1167 }
1168
1169 /// Set any additional parameter of the query string used in the request.
1170 /// It should be used to set parameters which are not yet available through their own
1171 /// setters.
1172 ///
1173 /// Please note that this method must not be used to set any of the known parameters
1174 /// which have their own setter method. If done anyway, the request will fail.
1175 ///
1176 /// # Additional Parameters
1177 ///
1178 /// * *$.xgafv* (query-string) - V1 error format.
1179 /// * *access_token* (query-string) - OAuth access token.
1180 /// * *alt* (query-string) - Data format for response.
1181 /// * *callback* (query-string) - JSONP
1182 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1183 /// * *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.
1184 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1185 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1186 /// * *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.
1187 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1188 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1189 pub fn param<T>(mut self, name: T, value: T) -> CommentSuggestscoreCall<'a, C>
1190 where
1191 T: AsRef<str>,
1192 {
1193 self._additional_params
1194 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1195 self
1196 }
1197
1198 /// Identifies the authorization scope for the method you are building.
1199 ///
1200 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1201 /// [`Scope::UserinfoEmail`].
1202 ///
1203 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1204 /// tokens for more than one scope.
1205 ///
1206 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1207 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1208 /// sufficient, a read-write scope will do as well.
1209 pub fn add_scope<St>(mut self, scope: St) -> CommentSuggestscoreCall<'a, C>
1210 where
1211 St: AsRef<str>,
1212 {
1213 self._scopes.insert(String::from(scope.as_ref()));
1214 self
1215 }
1216 /// Identifies the authorization scope(s) for the method you are building.
1217 ///
1218 /// See [`Self::add_scope()`] for details.
1219 pub fn add_scopes<I, St>(mut self, scopes: I) -> CommentSuggestscoreCall<'a, C>
1220 where
1221 I: IntoIterator<Item = St>,
1222 St: AsRef<str>,
1223 {
1224 self._scopes
1225 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1226 self
1227 }
1228
1229 /// Removes all scopes, and no default scope will be used either.
1230 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1231 /// for details).
1232 pub fn clear_scopes(mut self) -> CommentSuggestscoreCall<'a, C> {
1233 self._scopes.clear();
1234 self
1235 }
1236}