google_pagespeedonline2/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// ########
12// HUB ###
13// ######
14
15/// Central instance to access all Pagespeedonline related resource activities
16///
17/// # Examples
18///
19/// Instantiate a new hub
20///
21/// ```test_harness,no_run
22/// extern crate hyper;
23/// extern crate hyper_rustls;
24/// extern crate google_pagespeedonline2 as pagespeedonline2;
25/// use pagespeedonline2::{Result, Error};
26/// # async fn dox() {
27/// use pagespeedonline2::{Pagespeedonline, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
28///
29/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
30/// // `client_secret`, among other things.
31/// let secret: yup_oauth2::ApplicationSecret = Default::default();
32/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
33/// // unless you replace `None` with the desired Flow.
34/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
35/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
36/// // retrieve them from storage.
37/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
38/// .with_native_roots()
39/// .unwrap()
40/// .https_only()
41/// .enable_http2()
42/// .build();
43///
44/// let executor = hyper_util::rt::TokioExecutor::new();
45/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
46/// secret,
47/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
48/// yup_oauth2::client::CustomHyperClientBuilder::from(
49/// hyper_util::client::legacy::Client::builder(executor).build(connector),
50/// ),
51/// ).build().await.unwrap();
52///
53/// let client = hyper_util::client::legacy::Client::builder(
54/// hyper_util::rt::TokioExecutor::new()
55/// )
56/// .build(
57/// hyper_rustls::HttpsConnectorBuilder::new()
58/// .with_native_roots()
59/// .unwrap()
60/// .https_or_http()
61/// .enable_http2()
62/// .build()
63/// );
64/// let mut hub = Pagespeedonline::new(client, auth);
65/// // You can configure optional parameters by calling the respective setters at will, and
66/// // execute the final call using `doit()`.
67/// // Values shown here are possibly random and not representative !
68/// let result = hub.pagespeedapi().runpagespeed("url")
69/// .strategy("gubergren")
70/// .screenshot(false)
71/// .add_rule("dolor")
72/// .locale("ea")
73/// .filter_third_party_resources(true)
74/// .doit().await;
75///
76/// match result {
77/// Err(e) => match e {
78/// // The Error enum provides details about what exactly happened.
79/// // You can also just use its `Debug`, `Display` or `Error` traits
80/// Error::HttpError(_)
81/// |Error::Io(_)
82/// |Error::MissingAPIKey
83/// |Error::MissingToken(_)
84/// |Error::Cancelled
85/// |Error::UploadSizeLimitExceeded(_, _)
86/// |Error::Failure(_)
87/// |Error::BadRequest(_)
88/// |Error::FieldClash(_)
89/// |Error::JsonDecodeError(_, _) => println!("{}", e),
90/// },
91/// Ok(res) => println!("Success: {:?}", res),
92/// }
93/// # }
94/// ```
95#[derive(Clone)]
96pub struct Pagespeedonline<C> {
97 pub client: common::Client<C>,
98 pub auth: Box<dyn common::GetToken>,
99 _user_agent: String,
100 _base_url: String,
101 _root_url: String,
102}
103
104impl<C> common::Hub for Pagespeedonline<C> {}
105
106impl<'a, C> Pagespeedonline<C> {
107 pub fn new<A: 'static + common::GetToken>(
108 client: common::Client<C>,
109 auth: A,
110 ) -> Pagespeedonline<C> {
111 Pagespeedonline {
112 client,
113 auth: Box::new(auth),
114 _user_agent: "google-api-rust-client/7.0.0".to_string(),
115 _base_url: "https://www.googleapis.com/pagespeedonline/v2/".to_string(),
116 _root_url: "https://www.googleapis.com/".to_string(),
117 }
118 }
119
120 pub fn pagespeedapi(&'a self) -> PagespeedapiMethods<'a, C> {
121 PagespeedapiMethods { hub: self }
122 }
123
124 /// Set the user-agent header field to use in all requests to the server.
125 /// It defaults to `google-api-rust-client/7.0.0`.
126 ///
127 /// Returns the previously set user-agent.
128 pub fn user_agent(&mut self, agent_name: String) -> String {
129 std::mem::replace(&mut self._user_agent, agent_name)
130 }
131
132 /// Set the base url to use in all requests to the server.
133 /// It defaults to `https://www.googleapis.com/pagespeedonline/v2/`.
134 ///
135 /// Returns the previously set base url.
136 pub fn base_url(&mut self, new_base_url: String) -> String {
137 std::mem::replace(&mut self._base_url, new_base_url)
138 }
139
140 /// Set the root url to use in all requests to the server.
141 /// It defaults to `https://www.googleapis.com/`.
142 ///
143 /// Returns the previously set root url.
144 pub fn root_url(&mut self, new_root_url: String) -> String {
145 std::mem::replace(&mut self._root_url, new_root_url)
146 }
147}
148
149// ############
150// SCHEMAS ###
151// ##########
152/// There is no detailed description.
153///
154/// This type is not used in any activity, and only used as *part* of another schema.
155///
156#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
157#[serde_with::serde_as]
158#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
159pub struct PagespeedApiFormatStringV2 {
160 /// List of arguments for the format string.
161 pub args: Option<Vec<PagespeedApiFormatStringV2Args>>,
162 /// A localized format string with {{FOO}} placeholders, where 'FOO' is the key of the argument whose value should be substituted. For HYPERLINK arguments, the format string will instead contain {{BEGIN_FOO}} and {{END_FOO}} for the argument with key 'FOO'.
163 pub format: Option<String>,
164}
165
166impl common::Part for PagespeedApiFormatStringV2 {}
167
168/// There is no detailed description.
169///
170/// This type is not used in any activity, and only used as *part* of another schema.
171///
172#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
173#[serde_with::serde_as]
174#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
175pub struct PagespeedApiImageV2 {
176 /// Image data base64 encoded.
177 #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
178 pub data: Option<Vec<u8>>,
179 /// Height of screenshot in pixels.
180 pub height: Option<i32>,
181 /// Unique string key, if any, identifying this image.
182 pub key: Option<String>,
183 /// Mime type of image data (e.g. "image/jpeg").
184 pub mime_type: Option<String>,
185 /// The region of the page that is captured by this image, with dimensions measured in CSS pixels.
186 pub page_rect: Option<PagespeedApiImageV2PageRect>,
187 /// Width of screenshot in pixels.
188 pub width: Option<i32>,
189}
190
191impl common::Part for PagespeedApiImageV2 {}
192
193/// There is no detailed description.
194///
195/// # Activities
196///
197/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
198/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
199///
200/// * [runpagespeed pagespeedapi](PagespeedapiRunpagespeedCall) (response)
201#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
202#[serde_with::serde_as]
203#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
204pub struct Result {
205 /// The captcha verify result
206 #[serde(rename = "captchaResult")]
207 pub captcha_result: Option<String>,
208 /// Localized PageSpeed results. Contains a ruleResults entry for each PageSpeed rule instantiated and run by the server.
209 #[serde(rename = "formattedResults")]
210 pub formatted_results: Option<ResultFormattedResults>,
211 /// Canonicalized and final URL for the document, after following page redirects (if any).
212 pub id: Option<String>,
213 /// List of rules that were specified in the request, but which the server did not know how to instantiate.
214 #[serde(rename = "invalidRules")]
215 pub invalid_rules: Option<Vec<String>>,
216 /// Kind of result.
217 pub kind: Option<String>,
218 /// Summary statistics for the page, such as number of JavaScript bytes, number of HTML bytes, etc.
219 #[serde(rename = "pageStats")]
220 pub page_stats: Option<ResultPageStats>,
221 /// Response code for the document. 200 indicates a normal page load. 4xx/5xx indicates an error.
222 #[serde(rename = "responseCode")]
223 pub response_code: Option<i32>,
224 /// A map with one entry for each rule group in these results.
225 #[serde(rename = "ruleGroups")]
226 pub rule_groups: Option<HashMap<String, ResultRuleGroups>>,
227 /// Base64-encoded screenshot of the page that was analyzed.
228 pub screenshot: Option<PagespeedApiImageV2>,
229 /// Title of the page, as displayed in the browser's title bar.
230 pub title: Option<String>,
231 /// The version of PageSpeed used to generate these results.
232 pub version: Option<ResultVersion>,
233}
234
235impl common::ResponseResult for Result {}
236
237/// List of arguments for the format string.
238///
239/// This type is not used in any activity, and only used as *part* of another schema.
240///
241#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
242#[serde_with::serde_as]
243#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
244pub struct PagespeedApiFormatStringV2Args {
245 /// The placeholder key for this arg, as a string.
246 pub key: Option<String>,
247 /// The screen rectangles being referred to, with dimensions measured in CSS pixels. This is only ever used for SNAPSHOT_RECT arguments. If this is absent for a SNAPSHOT_RECT argument, it means that that argument refers to the entire snapshot.
248 pub rects: Option<Vec<PagespeedApiFormatStringV2ArgsRects>>,
249 /// Secondary screen rectangles being referred to, with dimensions measured in CSS pixels. This is only ever used for SNAPSHOT_RECT arguments.
250 pub secondary_rects: Option<Vec<PagespeedApiFormatStringV2ArgsSecondaryRects>>,
251 /// Type of argument. One of URL, STRING_LITERAL, INT_LITERAL, BYTES, DURATION, VERBATIM_STRING, PERCENTAGE, HYPERLINK, or SNAPSHOT_RECT.
252 #[serde(rename = "type")]
253 pub type_: Option<String>,
254 /// Argument value, as a localized string.
255 pub value: Option<String>,
256}
257
258impl common::NestedType for PagespeedApiFormatStringV2Args {}
259impl common::Part for PagespeedApiFormatStringV2Args {}
260
261/// The screen rectangles being referred to, with dimensions measured in CSS pixels. This is only ever used for SNAPSHOT_RECT arguments. If this is absent for a SNAPSHOT_RECT argument, it means that that argument refers to the entire snapshot.
262///
263/// This type is not used in any activity, and only used as *part* of another schema.
264///
265#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
266#[serde_with::serde_as]
267#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
268pub struct PagespeedApiFormatStringV2ArgsRects {
269 /// The height of the rect.
270 pub height: Option<i32>,
271 /// The left coordinate of the rect, in page coordinates.
272 pub left: Option<i32>,
273 /// The top coordinate of the rect, in page coordinates.
274 pub top: Option<i32>,
275 /// The width of the rect.
276 pub width: Option<i32>,
277}
278
279impl common::NestedType for PagespeedApiFormatStringV2ArgsRects {}
280impl common::Part for PagespeedApiFormatStringV2ArgsRects {}
281
282/// Secondary screen rectangles being referred to, with dimensions measured in CSS pixels. This is only ever used for SNAPSHOT_RECT arguments.
283///
284/// This type is not used in any activity, and only used as *part* of another schema.
285///
286#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
287#[serde_with::serde_as]
288#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
289pub struct PagespeedApiFormatStringV2ArgsSecondaryRects {
290 /// The height of the rect.
291 pub height: Option<i32>,
292 /// The left coordinate of the rect, in page coordinates.
293 pub left: Option<i32>,
294 /// The top coordinate of the rect, in page coordinates.
295 pub top: Option<i32>,
296 /// The width of the rect.
297 pub width: Option<i32>,
298}
299
300impl common::NestedType for PagespeedApiFormatStringV2ArgsSecondaryRects {}
301impl common::Part for PagespeedApiFormatStringV2ArgsSecondaryRects {}
302
303/// The region of the page that is captured by this image, with dimensions measured in CSS pixels.
304///
305/// This type is not used in any activity, and only used as *part* of another schema.
306///
307#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
308#[serde_with::serde_as]
309#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
310pub struct PagespeedApiImageV2PageRect {
311 /// The height of the rect.
312 pub height: Option<i32>,
313 /// The left coordinate of the rect, in page coordinates.
314 pub left: Option<i32>,
315 /// The top coordinate of the rect, in page coordinates.
316 pub top: Option<i32>,
317 /// The width of the rect.
318 pub width: Option<i32>,
319}
320
321impl common::NestedType for PagespeedApiImageV2PageRect {}
322impl common::Part for PagespeedApiImageV2PageRect {}
323
324/// Localized PageSpeed results. Contains a ruleResults entry for each PageSpeed rule instantiated and run by the server.
325///
326/// This type is not used in any activity, and only used as *part* of another schema.
327///
328#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
329#[serde_with::serde_as]
330#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
331pub struct ResultFormattedResults {
332 /// The locale of the formattedResults, e.g. "en_US".
333 pub locale: Option<String>,
334 /// Dictionary of formatted rule results, with one entry for each PageSpeed rule instantiated and run by the server.
335 #[serde(rename = "ruleResults")]
336 pub rule_results: Option<HashMap<String, ResultFormattedResultsRuleResults>>,
337}
338
339impl common::NestedType for ResultFormattedResults {}
340impl common::Part for ResultFormattedResults {}
341
342/// The enum-like identifier for this rule. For instance "EnableKeepAlive" or "AvoidCssImport". Not localized.
343///
344/// This type is not used in any activity, and only used as *part* of another schema.
345///
346#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
347#[serde_with::serde_as]
348#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
349pub struct ResultFormattedResultsRuleResults {
350 /// List of rule groups that this rule belongs to. Each entry in the list is one of "SPEED" or "USABILITY".
351 pub groups: Option<Vec<String>>,
352 /// Localized name of the rule, intended for presentation to a user.
353 #[serde(rename = "localizedRuleName")]
354 pub localized_rule_name: Option<String>,
355 /// The impact (unbounded floating point value) that implementing the suggestions for this rule would have on making the page faster. Impact is comparable between rules to determine which rule's suggestions would have a higher or lower impact on making a page faster. For instance, if enabling compression would save 1MB, while optimizing images would save 500kB, the enable compression rule would have 2x the impact of the image optimization rule, all other things being equal.
356 #[serde(rename = "ruleImpact")]
357 pub rule_impact: Option<f64>,
358 /// A brief summary description for the rule, indicating at a high level what should be done to follow the rule and what benefit can be gained by doing so.
359 pub summary: Option<PagespeedApiFormatStringV2>,
360 /// List of blocks of URLs. Each block may contain a heading and a list of URLs. Each URL may optionally include additional details.
361 #[serde(rename = "urlBlocks")]
362 pub url_blocks: Option<Vec<ResultFormattedResultsRuleResultsUrlBlocks>>,
363}
364
365impl common::NestedType for ResultFormattedResultsRuleResults {}
366impl common::Part for ResultFormattedResultsRuleResults {}
367
368/// List of blocks of URLs. Each block may contain a heading and a list of URLs. Each URL may optionally include additional details.
369///
370/// This type is not used in any activity, and only used as *part* of another schema.
371///
372#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
373#[serde_with::serde_as]
374#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
375pub struct ResultFormattedResultsRuleResultsUrlBlocks {
376 /// Heading to be displayed with the list of URLs.
377 pub header: Option<PagespeedApiFormatStringV2>,
378 /// List of entries that provide information about URLs in the url block. Optional.
379 pub urls: Option<Vec<ResultFormattedResultsRuleResultsUrlBlocksUrls>>,
380}
381
382impl common::NestedType for ResultFormattedResultsRuleResultsUrlBlocks {}
383impl common::Part for ResultFormattedResultsRuleResultsUrlBlocks {}
384
385/// List of entries that provide information about URLs in the url block. Optional.
386///
387/// This type is not used in any activity, and only used as *part* of another schema.
388///
389#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
390#[serde_with::serde_as]
391#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
392pub struct ResultFormattedResultsRuleResultsUrlBlocksUrls {
393 /// List of entries that provide additional details about a single URL. Optional.
394 pub details: Option<Vec<PagespeedApiFormatStringV2>>,
395 /// A format string that gives information about the URL, and a list of arguments for that format string.
396 pub result: Option<PagespeedApiFormatStringV2>,
397}
398
399impl common::NestedType for ResultFormattedResultsRuleResultsUrlBlocksUrls {}
400impl common::Part for ResultFormattedResultsRuleResultsUrlBlocksUrls {}
401
402/// Summary statistics for the page, such as number of JavaScript bytes, number of HTML bytes, etc.
403///
404/// This type is not used in any activity, and only used as *part* of another schema.
405///
406#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
407#[serde_with::serde_as]
408#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
409pub struct ResultPageStats {
410 /// Number of uncompressed response bytes for CSS resources on the page.
411 #[serde(rename = "cssResponseBytes")]
412 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
413 pub css_response_bytes: Option<i64>,
414 /// Number of response bytes for flash resources on the page.
415 #[serde(rename = "flashResponseBytes")]
416 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
417 pub flash_response_bytes: Option<i64>,
418 /// Number of uncompressed response bytes for the main HTML document and all iframes on the page.
419 #[serde(rename = "htmlResponseBytes")]
420 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
421 pub html_response_bytes: Option<i64>,
422 /// Number of response bytes for image resources on the page.
423 #[serde(rename = "imageResponseBytes")]
424 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
425 pub image_response_bytes: Option<i64>,
426 /// Number of uncompressed response bytes for JS resources on the page.
427 #[serde(rename = "javascriptResponseBytes")]
428 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
429 pub javascript_response_bytes: Option<i64>,
430 /// Number of CSS resources referenced by the page.
431 #[serde(rename = "numberCssResources")]
432 pub number_css_resources: Option<i32>,
433 /// Number of unique hosts referenced by the page.
434 #[serde(rename = "numberHosts")]
435 pub number_hosts: Option<i32>,
436 /// Number of JavaScript resources referenced by the page.
437 #[serde(rename = "numberJsResources")]
438 pub number_js_resources: Option<i32>,
439 /// Number of HTTP resources loaded by the page.
440 #[serde(rename = "numberResources")]
441 pub number_resources: Option<i32>,
442 /// Number of static (i.e. cacheable) resources on the page.
443 #[serde(rename = "numberStaticResources")]
444 pub number_static_resources: Option<i32>,
445 /// Number of response bytes for other resources on the page.
446 #[serde(rename = "otherResponseBytes")]
447 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
448 pub other_response_bytes: Option<i64>,
449 /// Number of uncompressed response bytes for text resources not covered by other statistics (i.e non-HTML, non-script, non-CSS resources) on the page.
450 #[serde(rename = "textResponseBytes")]
451 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
452 pub text_response_bytes: Option<i64>,
453 /// Total size of all request bytes sent by the page.
454 #[serde(rename = "totalRequestBytes")]
455 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
456 pub total_request_bytes: Option<i64>,
457}
458
459impl common::NestedType for ResultPageStats {}
460impl common::Part for ResultPageStats {}
461
462/// The name of this rule group: one of "SPEED" or "USABILITY".
463///
464/// This type is not used in any activity, and only used as *part* of another schema.
465///
466#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
467#[serde_with::serde_as]
468#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
469pub struct ResultRuleGroups {
470 /// The score (0-100) for this rule group, which indicates how much better a page could be in that category (e.g. how much faster, or how much more usable). A high score indicates little room for improvement, while a lower score indicates more room for improvement.
471 pub score: Option<i32>,
472}
473
474impl common::NestedType for ResultRuleGroups {}
475impl common::Part for ResultRuleGroups {}
476
477/// The version of PageSpeed used to generate these results.
478///
479/// This type is not used in any activity, and only used as *part* of another schema.
480///
481#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
482#[serde_with::serde_as]
483#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
484pub struct ResultVersion {
485 /// The major version number of PageSpeed used to generate these results.
486 pub major: Option<i32>,
487 /// The minor version number of PageSpeed used to generate these results.
488 pub minor: Option<i32>,
489}
490
491impl common::NestedType for ResultVersion {}
492impl common::Part for ResultVersion {}
493
494// ###################
495// MethodBuilders ###
496// #################
497
498/// A builder providing access to all methods supported on *pagespeedapi* resources.
499/// It is not used directly, but through the [`Pagespeedonline`] hub.
500///
501/// # Example
502///
503/// Instantiate a resource builder
504///
505/// ```test_harness,no_run
506/// extern crate hyper;
507/// extern crate hyper_rustls;
508/// extern crate google_pagespeedonline2 as pagespeedonline2;
509///
510/// # async fn dox() {
511/// use pagespeedonline2::{Pagespeedonline, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
512///
513/// let secret: yup_oauth2::ApplicationSecret = Default::default();
514/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
515/// .with_native_roots()
516/// .unwrap()
517/// .https_only()
518/// .enable_http2()
519/// .build();
520///
521/// let executor = hyper_util::rt::TokioExecutor::new();
522/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
523/// secret,
524/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
525/// yup_oauth2::client::CustomHyperClientBuilder::from(
526/// hyper_util::client::legacy::Client::builder(executor).build(connector),
527/// ),
528/// ).build().await.unwrap();
529///
530/// let client = hyper_util::client::legacy::Client::builder(
531/// hyper_util::rt::TokioExecutor::new()
532/// )
533/// .build(
534/// hyper_rustls::HttpsConnectorBuilder::new()
535/// .with_native_roots()
536/// .unwrap()
537/// .https_or_http()
538/// .enable_http2()
539/// .build()
540/// );
541/// let mut hub = Pagespeedonline::new(client, auth);
542/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
543/// // like `runpagespeed(...)`
544/// // to build up your call.
545/// let rb = hub.pagespeedapi();
546/// # }
547/// ```
548pub struct PagespeedapiMethods<'a, C>
549where
550 C: 'a,
551{
552 hub: &'a Pagespeedonline<C>,
553}
554
555impl<'a, C> common::MethodsBuilder for PagespeedapiMethods<'a, C> {}
556
557impl<'a, C> PagespeedapiMethods<'a, C> {
558 /// Create a builder to help you perform the following task:
559 ///
560 /// Runs PageSpeed analysis on the page at the specified URL, and returns PageSpeed scores, a list of suggestions to make that page faster, and other information.
561 ///
562 /// # Arguments
563 ///
564 /// * `url` - The URL to fetch and analyze
565 pub fn runpagespeed(&self, url: &str) -> PagespeedapiRunpagespeedCall<'a, C> {
566 PagespeedapiRunpagespeedCall {
567 hub: self.hub,
568 _url: url.to_string(),
569 _strategy: Default::default(),
570 _screenshot: Default::default(),
571 _rule: Default::default(),
572 _locale: Default::default(),
573 _filter_third_party_resources: Default::default(),
574 _delegate: Default::default(),
575 _additional_params: Default::default(),
576 }
577 }
578}
579
580// ###################
581// CallBuilders ###
582// #################
583
584/// Runs PageSpeed analysis on the page at the specified URL, and returns PageSpeed scores, a list of suggestions to make that page faster, and other information.
585///
586/// A builder for the *runpagespeed* method supported by a *pagespeedapi* resource.
587/// It is not used directly, but through a [`PagespeedapiMethods`] instance.
588///
589/// # Example
590///
591/// Instantiate a resource method builder
592///
593/// ```test_harness,no_run
594/// # extern crate hyper;
595/// # extern crate hyper_rustls;
596/// # extern crate google_pagespeedonline2 as pagespeedonline2;
597/// # async fn dox() {
598/// # use pagespeedonline2::{Pagespeedonline, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
599///
600/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
601/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
602/// # .with_native_roots()
603/// # .unwrap()
604/// # .https_only()
605/// # .enable_http2()
606/// # .build();
607///
608/// # let executor = hyper_util::rt::TokioExecutor::new();
609/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
610/// # secret,
611/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
612/// # yup_oauth2::client::CustomHyperClientBuilder::from(
613/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
614/// # ),
615/// # ).build().await.unwrap();
616///
617/// # let client = hyper_util::client::legacy::Client::builder(
618/// # hyper_util::rt::TokioExecutor::new()
619/// # )
620/// # .build(
621/// # hyper_rustls::HttpsConnectorBuilder::new()
622/// # .with_native_roots()
623/// # .unwrap()
624/// # .https_or_http()
625/// # .enable_http2()
626/// # .build()
627/// # );
628/// # let mut hub = Pagespeedonline::new(client, auth);
629/// // You can configure optional parameters by calling the respective setters at will, and
630/// // execute the final call using `doit()`.
631/// // Values shown here are possibly random and not representative !
632/// let result = hub.pagespeedapi().runpagespeed("url")
633/// .strategy("amet")
634/// .screenshot(true)
635/// .add_rule("sed")
636/// .locale("ut")
637/// .filter_third_party_resources(true)
638/// .doit().await;
639/// # }
640/// ```
641pub struct PagespeedapiRunpagespeedCall<'a, C>
642where
643 C: 'a,
644{
645 hub: &'a Pagespeedonline<C>,
646 _url: String,
647 _strategy: Option<String>,
648 _screenshot: Option<bool>,
649 _rule: Vec<String>,
650 _locale: Option<String>,
651 _filter_third_party_resources: Option<bool>,
652 _delegate: Option<&'a mut dyn common::Delegate>,
653 _additional_params: HashMap<String, String>,
654}
655
656impl<'a, C> common::CallBuilder for PagespeedapiRunpagespeedCall<'a, C> {}
657
658impl<'a, C> PagespeedapiRunpagespeedCall<'a, C>
659where
660 C: common::Connector,
661{
662 /// Perform the operation you have build so far.
663 pub async fn doit(mut self) -> common::Result<(common::Response, Result)> {
664 use std::borrow::Cow;
665 use std::io::{Read, Seek};
666
667 use common::{url::Params, ToParts};
668 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
669
670 let mut dd = common::DefaultDelegate;
671 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
672 dlg.begin(common::MethodInfo {
673 id: "pagespeedonline.pagespeedapi.runpagespeed",
674 http_method: hyper::Method::GET,
675 });
676
677 for &field in [
678 "alt",
679 "url",
680 "strategy",
681 "screenshot",
682 "rule",
683 "locale",
684 "filter_third_party_resources",
685 ]
686 .iter()
687 {
688 if self._additional_params.contains_key(field) {
689 dlg.finished(false);
690 return Err(common::Error::FieldClash(field));
691 }
692 }
693
694 let mut params = Params::with_capacity(8 + self._additional_params.len());
695 params.push("url", self._url);
696 if let Some(value) = self._strategy.as_ref() {
697 params.push("strategy", value);
698 }
699 if let Some(value) = self._screenshot.as_ref() {
700 params.push("screenshot", value.to_string());
701 }
702 if !self._rule.is_empty() {
703 for f in self._rule.iter() {
704 params.push("rule", f);
705 }
706 }
707 if let Some(value) = self._locale.as_ref() {
708 params.push("locale", value);
709 }
710 if let Some(value) = self._filter_third_party_resources.as_ref() {
711 params.push("filter_third_party_resources", value.to_string());
712 }
713
714 params.extend(self._additional_params.iter());
715
716 params.push("alt", "json");
717 let mut url = self.hub._base_url.clone() + "runPagespeed";
718
719 match dlg.api_key() {
720 Some(value) => params.push("key", value),
721 None => {
722 dlg.finished(false);
723 return Err(common::Error::MissingAPIKey);
724 }
725 }
726
727 let url = params.parse_with_url(&url);
728
729 loop {
730 let mut req_result = {
731 let client = &self.hub.client;
732 dlg.pre_request();
733 let mut req_builder = hyper::Request::builder()
734 .method(hyper::Method::GET)
735 .uri(url.as_str())
736 .header(USER_AGENT, self.hub._user_agent.clone());
737
738 let request = req_builder
739 .header(CONTENT_LENGTH, 0_u64)
740 .body(common::to_body::<String>(None));
741
742 client.request(request.unwrap()).await
743 };
744
745 match req_result {
746 Err(err) => {
747 if let common::Retry::After(d) = dlg.http_error(&err) {
748 sleep(d).await;
749 continue;
750 }
751 dlg.finished(false);
752 return Err(common::Error::HttpError(err));
753 }
754 Ok(res) => {
755 let (mut parts, body) = res.into_parts();
756 let mut body = common::Body::new(body);
757 if !parts.status.is_success() {
758 let bytes = common::to_bytes(body).await.unwrap_or_default();
759 let error = serde_json::from_str(&common::to_string(&bytes));
760 let response = common::to_response(parts, bytes.into());
761
762 if let common::Retry::After(d) =
763 dlg.http_failure(&response, error.as_ref().ok())
764 {
765 sleep(d).await;
766 continue;
767 }
768
769 dlg.finished(false);
770
771 return Err(match error {
772 Ok(value) => common::Error::BadRequest(value),
773 _ => common::Error::Failure(response),
774 });
775 }
776 let response = {
777 let bytes = common::to_bytes(body).await.unwrap_or_default();
778 let encoded = common::to_string(&bytes);
779 match serde_json::from_str(&encoded) {
780 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
781 Err(error) => {
782 dlg.response_json_decode_error(&encoded, &error);
783 return Err(common::Error::JsonDecodeError(
784 encoded.to_string(),
785 error,
786 ));
787 }
788 }
789 };
790
791 dlg.finished(true);
792 return Ok(response);
793 }
794 }
795 }
796 }
797
798 /// The URL to fetch and analyze
799 ///
800 /// Sets the *url* query property to the given value.
801 ///
802 /// Even though the property as already been set when instantiating this call,
803 /// we provide this method for API completeness.
804 pub fn url(mut self, new_value: &str) -> PagespeedapiRunpagespeedCall<'a, C> {
805 self._url = new_value.to_string();
806 self
807 }
808 /// The analysis strategy to use
809 ///
810 /// Sets the *strategy* query property to the given value.
811 pub fn strategy(mut self, new_value: &str) -> PagespeedapiRunpagespeedCall<'a, C> {
812 self._strategy = Some(new_value.to_string());
813 self
814 }
815 /// Indicates if binary data containing a screenshot should be included
816 ///
817 /// Sets the *screenshot* query property to the given value.
818 pub fn screenshot(mut self, new_value: bool) -> PagespeedapiRunpagespeedCall<'a, C> {
819 self._screenshot = Some(new_value);
820 self
821 }
822 /// A PageSpeed rule to run; if none are given, all rules are run
823 ///
824 /// Append the given value to the *rule* query property.
825 /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
826 pub fn add_rule(mut self, new_value: &str) -> PagespeedapiRunpagespeedCall<'a, C> {
827 self._rule.push(new_value.to_string());
828 self
829 }
830 /// The locale used to localize formatted results
831 ///
832 /// Sets the *locale* query property to the given value.
833 pub fn locale(mut self, new_value: &str) -> PagespeedapiRunpagespeedCall<'a, C> {
834 self._locale = Some(new_value.to_string());
835 self
836 }
837 /// Indicates if third party resources should be filtered out before PageSpeed analysis.
838 ///
839 /// Sets the *filter_third_party_resources* query property to the given value.
840 pub fn filter_third_party_resources(
841 mut self,
842 new_value: bool,
843 ) -> PagespeedapiRunpagespeedCall<'a, C> {
844 self._filter_third_party_resources = Some(new_value);
845 self
846 }
847 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
848 /// while executing the actual API request.
849 ///
850 /// ````text
851 /// It should be used to handle progress information, and to implement a certain level of resilience.
852 /// ````
853 ///
854 /// Sets the *delegate* property to the given value.
855 pub fn delegate(
856 mut self,
857 new_value: &'a mut dyn common::Delegate,
858 ) -> PagespeedapiRunpagespeedCall<'a, C> {
859 self._delegate = Some(new_value);
860 self
861 }
862
863 /// Set any additional parameter of the query string used in the request.
864 /// It should be used to set parameters which are not yet available through their own
865 /// setters.
866 ///
867 /// Please note that this method must not be used to set any of the known parameters
868 /// which have their own setter method. If done anyway, the request will fail.
869 ///
870 /// # Additional Parameters
871 ///
872 /// * *alt* (query-string) - Data format for the response.
873 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
874 /// * *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.
875 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
876 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
877 /// * *quotaUser* (query-string) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
878 /// * *userIp* (query-string) - Deprecated. Please use quotaUser instead.
879 pub fn param<T>(mut self, name: T, value: T) -> PagespeedapiRunpagespeedCall<'a, C>
880 where
881 T: AsRef<str>,
882 {
883 self._additional_params
884 .insert(name.as_ref().to_string(), value.as_ref().to_string());
885 self
886 }
887}