google_webfonts1/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 Webfonts 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_webfonts1 as webfonts1;
25/// use webfonts1::{Result, Error};
26/// # async fn dox() {
27/// use webfonts1::{Webfonts, 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 = Webfonts::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.webfonts().list()
69/// .subset("amet.")
70/// .sort("duo")
71/// .add_family("ipsum")
72/// .category("gubergren")
73/// .add_capability("Lorem")
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 Webfonts<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 Webfonts<C> {}
105
106impl<'a, C> Webfonts<C> {
107 pub fn new<A: 'static + common::GetToken>(client: common::Client<C>, auth: A) -> Webfonts<C> {
108 Webfonts {
109 client,
110 auth: Box::new(auth),
111 _user_agent: "google-api-rust-client/7.0.0".to_string(),
112 _base_url: "https://webfonts.googleapis.com/".to_string(),
113 _root_url: "https://webfonts.googleapis.com/".to_string(),
114 }
115 }
116
117 pub fn webfonts(&'a self) -> WebfontMethods<'a, C> {
118 WebfontMethods { hub: self }
119 }
120
121 /// Set the user-agent header field to use in all requests to the server.
122 /// It defaults to `google-api-rust-client/7.0.0`.
123 ///
124 /// Returns the previously set user-agent.
125 pub fn user_agent(&mut self, agent_name: String) -> String {
126 std::mem::replace(&mut self._user_agent, agent_name)
127 }
128
129 /// Set the base url to use in all requests to the server.
130 /// It defaults to `https://webfonts.googleapis.com/`.
131 ///
132 /// Returns the previously set base url.
133 pub fn base_url(&mut self, new_base_url: String) -> String {
134 std::mem::replace(&mut self._base_url, new_base_url)
135 }
136
137 /// Set the root url to use in all requests to the server.
138 /// It defaults to `https://webfonts.googleapis.com/`.
139 ///
140 /// Returns the previously set root url.
141 pub fn root_url(&mut self, new_root_url: String) -> String {
142 std::mem::replace(&mut self._root_url, new_root_url)
143 }
144}
145
146// ############
147// SCHEMAS ###
148// ##########
149/// Metadata for a variable font axis.
150///
151/// This type is not used in any activity, and only used as *part* of another schema.
152///
153#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
154#[serde_with::serde_as]
155#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
156pub struct Axis {
157 /// maximum value
158 pub end: Option<f32>,
159 /// minimum value
160 pub start: Option<f32>,
161 /// tag name.
162 pub tag: Option<String>,
163}
164
165impl common::Part for Axis {}
166
167/// Metadata for a tag.
168///
169/// This type is not used in any activity, and only used as *part* of another schema.
170///
171#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
172#[serde_with::serde_as]
173#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
174pub struct Tag {
175 /// The name of the tag.
176 pub name: Option<String>,
177 /// The weight of the tag.
178 pub weight: Option<f32>,
179}
180
181impl common::Part for Tag {}
182
183/// Metadata describing a family of fonts.
184///
185/// # Activities
186///
187/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
188/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
189///
190/// * [list webfonts](WebfontListCall) (none)
191#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
192#[serde_with::serde_as]
193#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
194pub struct Webfont {
195 /// Axis for variable fonts.
196 pub axes: Option<Vec<Axis>>,
197 /// The category of the font.
198 pub category: Option<String>,
199 /// The color format(s) available for this family.
200 #[serde(rename = "colorCapabilities")]
201 pub color_capabilities: Option<Vec<String>>,
202 /// The name of the font.
203 pub family: Option<String>,
204 /// The font files (with all supported scripts) for each one of the available variants, as a key : value map.
205 pub files: Option<HashMap<String, String>>,
206 /// This kind represents a webfont object in the webfonts service.
207 pub kind: Option<String>,
208 /// The date (format "yyyy-MM-dd") the font was modified for the last time.
209 #[serde(rename = "lastModified")]
210 pub last_modified: Option<String>,
211 /// Font URL for menu subset, a subset of the font that is enough to display the font name
212 pub menu: Option<String>,
213 /// The scripts supported by the font.
214 pub subsets: Option<Vec<String>>,
215 /// The tags that apply to this family.
216 pub tags: Option<Vec<Tag>>,
217 /// The available variants for the font.
218 pub variants: Option<Vec<String>>,
219 /// The font version.
220 pub version: Option<String>,
221}
222
223impl common::Resource for Webfont {}
224
225/// Response containing the list of fonts currently served by the Google Fonts API.
226///
227/// # Activities
228///
229/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
230/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
231///
232/// * [list webfonts](WebfontListCall) (response)
233#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
234#[serde_with::serde_as]
235#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
236pub struct WebfontList {
237 /// The list of fonts currently served by the Google Fonts API.
238 pub items: Option<Vec<Webfont>>,
239 /// This kind represents a list of webfont objects in the webfonts service.
240 pub kind: Option<String>,
241}
242
243impl common::ResponseResult for WebfontList {}
244
245// ###################
246// MethodBuilders ###
247// #################
248
249/// A builder providing access to all methods supported on *webfont* resources.
250/// It is not used directly, but through the [`Webfonts`] hub.
251///
252/// # Example
253///
254/// Instantiate a resource builder
255///
256/// ```test_harness,no_run
257/// extern crate hyper;
258/// extern crate hyper_rustls;
259/// extern crate google_webfonts1 as webfonts1;
260///
261/// # async fn dox() {
262/// use webfonts1::{Webfonts, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
263///
264/// let secret: yup_oauth2::ApplicationSecret = Default::default();
265/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
266/// .with_native_roots()
267/// .unwrap()
268/// .https_only()
269/// .enable_http2()
270/// .build();
271///
272/// let executor = hyper_util::rt::TokioExecutor::new();
273/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
274/// secret,
275/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
276/// yup_oauth2::client::CustomHyperClientBuilder::from(
277/// hyper_util::client::legacy::Client::builder(executor).build(connector),
278/// ),
279/// ).build().await.unwrap();
280///
281/// let client = hyper_util::client::legacy::Client::builder(
282/// hyper_util::rt::TokioExecutor::new()
283/// )
284/// .build(
285/// hyper_rustls::HttpsConnectorBuilder::new()
286/// .with_native_roots()
287/// .unwrap()
288/// .https_or_http()
289/// .enable_http2()
290/// .build()
291/// );
292/// let mut hub = Webfonts::new(client, auth);
293/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
294/// // like `list(...)`
295/// // to build up your call.
296/// let rb = hub.webfonts();
297/// # }
298/// ```
299pub struct WebfontMethods<'a, C>
300where
301 C: 'a,
302{
303 hub: &'a Webfonts<C>,
304}
305
306impl<'a, C> common::MethodsBuilder for WebfontMethods<'a, C> {}
307
308impl<'a, C> WebfontMethods<'a, C> {
309 /// Create a builder to help you perform the following task:
310 ///
311 /// Retrieves the list of fonts currently served by the Google Fonts Developer API.
312 pub fn list(&self) -> WebfontListCall<'a, C> {
313 WebfontListCall {
314 hub: self.hub,
315 _subset: Default::default(),
316 _sort: Default::default(),
317 _family: Default::default(),
318 _category: Default::default(),
319 _capability: Default::default(),
320 _delegate: Default::default(),
321 _additional_params: Default::default(),
322 }
323 }
324}
325
326// ###################
327// CallBuilders ###
328// #################
329
330/// Retrieves the list of fonts currently served by the Google Fonts Developer API.
331///
332/// A builder for the *list* method supported by a *webfont* resource.
333/// It is not used directly, but through a [`WebfontMethods`] instance.
334///
335/// # Example
336///
337/// Instantiate a resource method builder
338///
339/// ```test_harness,no_run
340/// # extern crate hyper;
341/// # extern crate hyper_rustls;
342/// # extern crate google_webfonts1 as webfonts1;
343/// # async fn dox() {
344/// # use webfonts1::{Webfonts, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
345///
346/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
347/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
348/// # .with_native_roots()
349/// # .unwrap()
350/// # .https_only()
351/// # .enable_http2()
352/// # .build();
353///
354/// # let executor = hyper_util::rt::TokioExecutor::new();
355/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
356/// # secret,
357/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
358/// # yup_oauth2::client::CustomHyperClientBuilder::from(
359/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
360/// # ),
361/// # ).build().await.unwrap();
362///
363/// # let client = hyper_util::client::legacy::Client::builder(
364/// # hyper_util::rt::TokioExecutor::new()
365/// # )
366/// # .build(
367/// # hyper_rustls::HttpsConnectorBuilder::new()
368/// # .with_native_roots()
369/// # .unwrap()
370/// # .https_or_http()
371/// # .enable_http2()
372/// # .build()
373/// # );
374/// # let mut hub = Webfonts::new(client, auth);
375/// // You can configure optional parameters by calling the respective setters at will, and
376/// // execute the final call using `doit()`.
377/// // Values shown here are possibly random and not representative !
378/// let result = hub.webfonts().list()
379/// .subset("gubergren")
380/// .sort("eos")
381/// .add_family("dolor")
382/// .category("ea")
383/// .add_capability("ipsum")
384/// .doit().await;
385/// # }
386/// ```
387pub struct WebfontListCall<'a, C>
388where
389 C: 'a,
390{
391 hub: &'a Webfonts<C>,
392 _subset: Option<String>,
393 _sort: Option<String>,
394 _family: Vec<String>,
395 _category: Option<String>,
396 _capability: Vec<String>,
397 _delegate: Option<&'a mut dyn common::Delegate>,
398 _additional_params: HashMap<String, String>,
399}
400
401impl<'a, C> common::CallBuilder for WebfontListCall<'a, C> {}
402
403impl<'a, C> WebfontListCall<'a, C>
404where
405 C: common::Connector,
406{
407 /// Perform the operation you have build so far.
408 pub async fn doit(mut self) -> common::Result<(common::Response, WebfontList)> {
409 use std::borrow::Cow;
410 use std::io::{Read, Seek};
411
412 use common::{url::Params, ToParts};
413 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
414
415 let mut dd = common::DefaultDelegate;
416 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
417 dlg.begin(common::MethodInfo {
418 id: "webfonts.webfonts.list",
419 http_method: hyper::Method::GET,
420 });
421
422 for &field in ["alt", "subset", "sort", "family", "category", "capability"].iter() {
423 if self._additional_params.contains_key(field) {
424 dlg.finished(false);
425 return Err(common::Error::FieldClash(field));
426 }
427 }
428
429 let mut params = Params::with_capacity(7 + self._additional_params.len());
430 if let Some(value) = self._subset.as_ref() {
431 params.push("subset", value);
432 }
433 if let Some(value) = self._sort.as_ref() {
434 params.push("sort", value);
435 }
436 if !self._family.is_empty() {
437 for f in self._family.iter() {
438 params.push("family", f);
439 }
440 }
441 if let Some(value) = self._category.as_ref() {
442 params.push("category", value);
443 }
444 if !self._capability.is_empty() {
445 for f in self._capability.iter() {
446 params.push("capability", f);
447 }
448 }
449
450 params.extend(self._additional_params.iter());
451
452 params.push("alt", "json");
453 let mut url = self.hub._base_url.clone() + "v1/webfonts";
454
455 match dlg.api_key() {
456 Some(value) => params.push("key", value),
457 None => {
458 dlg.finished(false);
459 return Err(common::Error::MissingAPIKey);
460 }
461 }
462
463 let url = params.parse_with_url(&url);
464
465 loop {
466 let mut req_result = {
467 let client = &self.hub.client;
468 dlg.pre_request();
469 let mut req_builder = hyper::Request::builder()
470 .method(hyper::Method::GET)
471 .uri(url.as_str())
472 .header(USER_AGENT, self.hub._user_agent.clone());
473
474 let request = req_builder
475 .header(CONTENT_LENGTH, 0_u64)
476 .body(common::to_body::<String>(None));
477
478 client.request(request.unwrap()).await
479 };
480
481 match req_result {
482 Err(err) => {
483 if let common::Retry::After(d) = dlg.http_error(&err) {
484 sleep(d).await;
485 continue;
486 }
487 dlg.finished(false);
488 return Err(common::Error::HttpError(err));
489 }
490 Ok(res) => {
491 let (mut parts, body) = res.into_parts();
492 let mut body = common::Body::new(body);
493 if !parts.status.is_success() {
494 let bytes = common::to_bytes(body).await.unwrap_or_default();
495 let error = serde_json::from_str(&common::to_string(&bytes));
496 let response = common::to_response(parts, bytes.into());
497
498 if let common::Retry::After(d) =
499 dlg.http_failure(&response, error.as_ref().ok())
500 {
501 sleep(d).await;
502 continue;
503 }
504
505 dlg.finished(false);
506
507 return Err(match error {
508 Ok(value) => common::Error::BadRequest(value),
509 _ => common::Error::Failure(response),
510 });
511 }
512 let response = {
513 let bytes = common::to_bytes(body).await.unwrap_or_default();
514 let encoded = common::to_string(&bytes);
515 match serde_json::from_str(&encoded) {
516 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
517 Err(error) => {
518 dlg.response_json_decode_error(&encoded, &error);
519 return Err(common::Error::JsonDecodeError(
520 encoded.to_string(),
521 error,
522 ));
523 }
524 }
525 };
526
527 dlg.finished(true);
528 return Ok(response);
529 }
530 }
531 }
532 }
533
534 /// Filters by Webfont.subset, if subset is found in Webfont.subsets. If not set, returns all families.
535 ///
536 /// Sets the *subset* query property to the given value.
537 pub fn subset(mut self, new_value: &str) -> WebfontListCall<'a, C> {
538 self._subset = Some(new_value.to_string());
539 self
540 }
541 /// Enables sorting of the list.
542 ///
543 /// Sets the *sort* query property to the given value.
544 pub fn sort(mut self, new_value: &str) -> WebfontListCall<'a, C> {
545 self._sort = Some(new_value.to_string());
546 self
547 }
548 /// Filters by Webfont.family, using literal match. If not set, returns all families
549 ///
550 /// Append the given value to the *family* query property.
551 /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
552 pub fn add_family(mut self, new_value: &str) -> WebfontListCall<'a, C> {
553 self._family.push(new_value.to_string());
554 self
555 }
556 /// Filters by Webfont.category, if category is found in Webfont.categories. If not set, returns all families.
557 ///
558 /// Sets the *category* query property to the given value.
559 pub fn category(mut self, new_value: &str) -> WebfontListCall<'a, C> {
560 self._category = Some(new_value.to_string());
561 self
562 }
563 /// Controls the font urls in `Webfont.files`, by default, static ttf fonts are sent.
564 ///
565 /// Append the given value to the *capability* query property.
566 /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters.
567 pub fn add_capability(mut self, new_value: &str) -> WebfontListCall<'a, C> {
568 self._capability.push(new_value.to_string());
569 self
570 }
571 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
572 /// while executing the actual API request.
573 ///
574 /// ````text
575 /// It should be used to handle progress information, and to implement a certain level of resilience.
576 /// ````
577 ///
578 /// Sets the *delegate* property to the given value.
579 pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> WebfontListCall<'a, C> {
580 self._delegate = Some(new_value);
581 self
582 }
583
584 /// Set any additional parameter of the query string used in the request.
585 /// It should be used to set parameters which are not yet available through their own
586 /// setters.
587 ///
588 /// Please note that this method must not be used to set any of the known parameters
589 /// which have their own setter method. If done anyway, the request will fail.
590 ///
591 /// # Additional Parameters
592 ///
593 /// * *$.xgafv* (query-string) - V1 error format.
594 /// * *access_token* (query-string) - OAuth access token.
595 /// * *alt* (query-string) - Data format for response.
596 /// * *callback* (query-string) - JSONP
597 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
598 /// * *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.
599 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
600 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
601 /// * *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.
602 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
603 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
604 pub fn param<T>(mut self, name: T, value: T) -> WebfontListCall<'a, C>
605 where
606 T: AsRef<str>,
607 {
608 self._additional_params
609 .insert(name.as_ref().to_string(), value.as_ref().to_string());
610 self
611 }
612}