google_homegraph1/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 /// Private Service: https://www.googleapis.com/auth/homegraph
17 Full,
18}
19
20impl AsRef<str> for Scope {
21 fn as_ref(&self) -> &str {
22 match *self {
23 Scope::Full => "https://www.googleapis.com/auth/homegraph",
24 }
25 }
26}
27
28#[allow(clippy::derivable_impls)]
29impl Default for Scope {
30 fn default() -> Scope {
31 Scope::Full
32 }
33}
34
35// ########
36// HUB ###
37// ######
38
39/// Central instance to access all HomeGraphService 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_homegraph1 as homegraph1;
49/// use homegraph1::api::QueryRequest;
50/// use homegraph1::{Result, Error};
51/// # async fn dox() {
52/// use homegraph1::{HomeGraphService, 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 = HomeGraphService::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 = QueryRequest::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.devices().query(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 HomeGraphService<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 HomeGraphService<C> {}
130
131impl<'a, C> HomeGraphService<C> {
132 pub fn new<A: 'static + common::GetToken>(
133 client: common::Client<C>,
134 auth: A,
135 ) -> HomeGraphService<C> {
136 HomeGraphService {
137 client,
138 auth: Box::new(auth),
139 _user_agent: "google-api-rust-client/7.0.0".to_string(),
140 _base_url: "https://homegraph.googleapis.com/".to_string(),
141 _root_url: "https://homegraph.googleapis.com/".to_string(),
142 }
143 }
144
145 pub fn agent_users(&'a self) -> AgentUserMethods<'a, C> {
146 AgentUserMethods { hub: self }
147 }
148 pub fn devices(&'a self) -> DeviceMethods<'a, C> {
149 DeviceMethods { hub: self }
150 }
151
152 /// Set the user-agent header field to use in all requests to the server.
153 /// It defaults to `google-api-rust-client/7.0.0`.
154 ///
155 /// Returns the previously set user-agent.
156 pub fn user_agent(&mut self, agent_name: String) -> String {
157 std::mem::replace(&mut self._user_agent, agent_name)
158 }
159
160 /// Set the base url to use in all requests to the server.
161 /// It defaults to `https://homegraph.googleapis.com/`.
162 ///
163 /// Returns the previously set base url.
164 pub fn base_url(&mut self, new_base_url: String) -> String {
165 std::mem::replace(&mut self._base_url, new_base_url)
166 }
167
168 /// Set the root url to use in all requests to the server.
169 /// It defaults to `https://homegraph.googleapis.com/`.
170 ///
171 /// Returns the previously set root url.
172 pub fn root_url(&mut self, new_root_url: String) -> String {
173 std::mem::replace(&mut self._root_url, new_root_url)
174 }
175}
176
177// ############
178// SCHEMAS ###
179// ##########
180/// Third-party device ID for one device.
181///
182/// This type is not used in any activity, and only used as *part* of another schema.
183///
184#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
185#[serde_with::serde_as]
186#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
187pub struct AgentDeviceId {
188 /// Third-party device ID.
189 pub id: Option<String>,
190}
191
192impl common::Part for AgentDeviceId {}
193
194/// Alternate third-party device ID.
195///
196/// This type is not used in any activity, and only used as *part* of another schema.
197///
198#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
199#[serde_with::serde_as]
200#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
201pub struct AgentOtherDeviceId {
202 /// Project ID for your smart home Action.
203 #[serde(rename = "agentId")]
204 pub agent_id: Option<String>,
205 /// Unique third-party device ID.
206 #[serde(rename = "deviceId")]
207 pub device_id: Option<String>,
208}
209
210impl common::Part for AgentOtherDeviceId {}
211
212/// Third-party device definition.
213///
214/// # Activities
215///
216/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
217/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
218///
219/// * [query devices](DeviceQueryCall) (none)
220/// * [report state and notification devices](DeviceReportStateAndNotificationCall) (none)
221/// * [request sync devices](DeviceRequestSyncCall) (none)
222/// * [sync devices](DeviceSyncCall) (none)
223#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
224#[serde_with::serde_as]
225#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
226pub struct Device {
227 /// Attributes for the traits supported by the device.
228 pub attributes: Option<HashMap<String, serde_json::Value>>,
229 /// Custom device attributes stored in Home Graph and provided to your smart home Action in each [QUERY](https://developers.home.google.com/cloud-to-cloud/intents/query) and [EXECUTE](https://developers.home.google.com/cloud-to-cloud/intents/execute) intent. Data in this object has a few constraints: No sensitive information, including but not limited to Personally Identifiable Information.
230 #[serde(rename = "customData")]
231 pub custom_data: Option<HashMap<String, serde_json::Value>>,
232 /// Device manufacturer, model, hardware version, and software version.
233 #[serde(rename = "deviceInfo")]
234 pub device_info: Option<DeviceInfo>,
235 /// Third-party device ID.
236 pub id: Option<String>,
237 /// Names given to this device by your smart home Action.
238 pub name: Option<DeviceNames>,
239 /// Indicates whether your smart home Action will report notifications to Google for this device via ReportStateAndNotification. If your smart home Action enables users to control device notifications, you should update this field and call RequestSyncDevices.
240 #[serde(rename = "notificationSupportedByAgent")]
241 pub notification_supported_by_agent: Option<bool>,
242 /// Alternate IDs associated with this device. This is used to identify cloud synced devices enabled for [local fulfillment](https://developers.home.google.com/local-home/overview).
243 #[serde(rename = "otherDeviceIds")]
244 pub other_device_ids: Option<Vec<AgentOtherDeviceId>>,
245 /// Suggested name for the room where this device is installed. Google attempts to use this value during user setup.
246 #[serde(rename = "roomHint")]
247 pub room_hint: Option<String>,
248 /// Suggested name for the structure where this device is installed. Google attempts to use this value during user setup.
249 #[serde(rename = "structureHint")]
250 pub structure_hint: Option<String>,
251 /// Traits supported by the device. See [device traits](https://developers.home.google.com/cloud-to-cloud/traits).
252 pub traits: Option<Vec<String>>,
253 /// Hardware type of the device. See [device types](https://developers.home.google.com/cloud-to-cloud/guides).
254 #[serde(rename = "type")]
255 pub type_: Option<String>,
256 /// Indicates whether your smart home Action will report state of this device to Google via ReportStateAndNotification.
257 #[serde(rename = "willReportState")]
258 pub will_report_state: Option<bool>,
259}
260
261impl common::Resource for Device {}
262
263/// Device information.
264///
265/// This type is not used in any activity, and only used as *part* of another schema.
266///
267#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
268#[serde_with::serde_as]
269#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
270pub struct DeviceInfo {
271 /// Device hardware version.
272 #[serde(rename = "hwVersion")]
273 pub hw_version: Option<String>,
274 /// Device manufacturer.
275 pub manufacturer: Option<String>,
276 /// Device model.
277 pub model: Option<String>,
278 /// Device software version.
279 #[serde(rename = "swVersion")]
280 pub sw_version: Option<String>,
281}
282
283impl common::Part for DeviceInfo {}
284
285/// Identifiers used to describe the device.
286///
287/// This type is not used in any activity, and only used as *part* of another schema.
288///
289#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
290#[serde_with::serde_as]
291#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
292pub struct DeviceNames {
293 /// List of names provided by the manufacturer rather than the user, such as serial numbers, SKUs, etc.
294 #[serde(rename = "defaultNames")]
295 pub default_names: Option<Vec<String>>,
296 /// Primary name of the device, generally provided by the user.
297 pub name: Option<String>,
298 /// Additional names provided by the user for the device.
299 pub nicknames: Option<Vec<String>>,
300}
301
302impl common::Part for DeviceNames {}
303
304/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
305///
306/// # Activities
307///
308/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
309/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
310///
311/// * [delete agent users](AgentUserDeleteCall) (response)
312#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
313#[serde_with::serde_as]
314#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
315pub struct Empty {
316 _never_set: Option<bool>,
317}
318
319impl common::ResponseResult for Empty {}
320
321/// Request type for the [`Query`](#google.home.graph.v1.HomeGraphApiService.Query) call.
322///
323/// # Activities
324///
325/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
326/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
327///
328/// * [query devices](DeviceQueryCall) (request)
329#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
330#[serde_with::serde_as]
331#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
332pub struct QueryRequest {
333 /// Required. Third-party user ID.
334 #[serde(rename = "agentUserId")]
335 pub agent_user_id: Option<String>,
336 /// Required. Inputs containing third-party device IDs for which to get the device states.
337 pub inputs: Option<Vec<QueryRequestInput>>,
338 /// Request ID used for debugging.
339 #[serde(rename = "requestId")]
340 pub request_id: Option<String>,
341}
342
343impl common::RequestValue for QueryRequest {}
344
345/// Device ID inputs to QueryRequest.
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 QueryRequestInput {
353 /// Payload containing third-party device IDs.
354 pub payload: Option<QueryRequestPayload>,
355}
356
357impl common::Part for QueryRequestInput {}
358
359/// Payload containing device IDs.
360///
361/// This type is not used in any activity, and only used as *part* of another schema.
362///
363#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
364#[serde_with::serde_as]
365#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
366pub struct QueryRequestPayload {
367 /// Third-party device IDs for which to get the device states.
368 pub devices: Option<Vec<AgentDeviceId>>,
369}
370
371impl common::Part for QueryRequestPayload {}
372
373/// Response type for the [`Query`](#google.home.graph.v1.HomeGraphApiService.Query) call. This should follow the same format as the Google smart home `action.devices.QUERY` [response](https://developers.home.google.com/cloud-to-cloud/intents/query). Example: `json { "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf", "payload": { "devices": { "123": { "on": true, "online": true }, "456": { "on": true, "online": true, "brightness": 80, "color": { "name": "cerulean", "spectrumRGB": 31655 } } } } } `
374///
375/// # Activities
376///
377/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
378/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
379///
380/// * [query devices](DeviceQueryCall) (response)
381#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
382#[serde_with::serde_as]
383#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
384pub struct QueryResponse {
385 /// Device states for the devices given in the request.
386 pub payload: Option<QueryResponsePayload>,
387 /// Request ID used for debugging. Copied from the request.
388 #[serde(rename = "requestId")]
389 pub request_id: Option<String>,
390}
391
392impl common::ResponseResult for QueryResponse {}
393
394/// Payload containing device states information.
395///
396/// This type is not used in any activity, and only used as *part* of another schema.
397///
398#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
399#[serde_with::serde_as]
400#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
401pub struct QueryResponsePayload {
402 /// States of the devices. Map of third-party device ID to struct of device states.
403 pub devices: Option<HashMap<String, HashMap<String, serde_json::Value>>>,
404}
405
406impl common::Part for QueryResponsePayload {}
407
408/// The states and notifications specific to a device.
409///
410/// This type is not used in any activity, and only used as *part* of another schema.
411///
412#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
413#[serde_with::serde_as]
414#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
415pub struct ReportStateAndNotificationDevice {
416 /// Notifications metadata for devices. See the **Device NOTIFICATIONS** section of the individual trait [reference guides](https://developers.home.google.com/cloud-to-cloud/traits).
417 pub notifications: Option<HashMap<String, serde_json::Value>>,
418 /// States of devices to update. See the **Device STATES** section of the individual trait [reference guides](https://developers.home.google.com/cloud-to-cloud/traits).
419 pub states: Option<HashMap<String, serde_json::Value>>,
420}
421
422impl common::Part for ReportStateAndNotificationDevice {}
423
424/// Request type for the [`ReportStateAndNotification`](#google.home.graph.v1.HomeGraphApiService.ReportStateAndNotification) call. It may include states, notifications, or both. States and notifications are defined per `device_id` (for example, “123” and “456” in the following example). Example: `json { "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf", "agentUserId": "1234", "payload": { "devices": { "states": { "123": { "on": true }, "456": { "on": true, "brightness": 10 } }, } } } `
425///
426/// # Activities
427///
428/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
429/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
430///
431/// * [report state and notification devices](DeviceReportStateAndNotificationCall) (request)
432#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
433#[serde_with::serde_as]
434#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
435pub struct ReportStateAndNotificationRequest {
436 /// Required. Third-party user ID.
437 #[serde(rename = "agentUserId")]
438 pub agent_user_id: Option<String>,
439 /// Unique identifier per event (for example, a doorbell press).
440 #[serde(rename = "eventId")]
441 pub event_id: Option<String>,
442 /// Deprecated.
443 #[serde(rename = "followUpToken")]
444 pub follow_up_token: Option<String>,
445 /// Required. State of devices to update and notification metadata for devices.
446 pub payload: Option<StateAndNotificationPayload>,
447 /// Request ID used for debugging.
448 #[serde(rename = "requestId")]
449 pub request_id: Option<String>,
450}
451
452impl common::RequestValue for ReportStateAndNotificationRequest {}
453
454/// Response type for the [`ReportStateAndNotification`](#google.home.graph.v1.HomeGraphApiService.ReportStateAndNotification) call.
455///
456/// # Activities
457///
458/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
459/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
460///
461/// * [report state and notification devices](DeviceReportStateAndNotificationCall) (response)
462#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
463#[serde_with::serde_as]
464#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
465pub struct ReportStateAndNotificationResponse {
466 /// Request ID copied from ReportStateAndNotificationRequest.
467 #[serde(rename = "requestId")]
468 pub request_id: Option<String>,
469}
470
471impl common::ResponseResult for ReportStateAndNotificationResponse {}
472
473/// Request type for the [`RequestSyncDevices`](#google.home.graph.v1.HomeGraphApiService.RequestSyncDevices) call.
474///
475/// # Activities
476///
477/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
478/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
479///
480/// * [request sync devices](DeviceRequestSyncCall) (request)
481#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
482#[serde_with::serde_as]
483#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
484pub struct RequestSyncDevicesRequest {
485 /// Required. Third-party user ID.
486 #[serde(rename = "agentUserId")]
487 pub agent_user_id: Option<String>,
488 /// Optional. If set, the request will be added to a queue and a response will be returned immediately. This enables concurrent requests for the given `agent_user_id`, but the caller will not receive any error responses.
489 #[serde(rename = "async")]
490 pub async_: Option<bool>,
491}
492
493impl common::RequestValue for RequestSyncDevicesRequest {}
494
495/// Response type for the [`RequestSyncDevices`](#google.home.graph.v1.HomeGraphApiService.RequestSyncDevices) call. Intentionally empty upon success. An HTTP response code is returned with more details upon failure.
496///
497/// # Activities
498///
499/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
500/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
501///
502/// * [request sync devices](DeviceRequestSyncCall) (response)
503#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
504#[serde_with::serde_as]
505#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
506pub struct RequestSyncDevicesResponse {
507 _never_set: Option<bool>,
508}
509
510impl common::ResponseResult for RequestSyncDevicesResponse {}
511
512/// Payload containing the state and notification information for devices.
513///
514/// This type is not used in any activity, and only used as *part* of another schema.
515///
516#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
517#[serde_with::serde_as]
518#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
519pub struct StateAndNotificationPayload {
520 /// The devices for updating state and sending notifications.
521 pub devices: Option<ReportStateAndNotificationDevice>,
522}
523
524impl common::Part for StateAndNotificationPayload {}
525
526/// Request type for the [`Sync`](#google.home.graph.v1.HomeGraphApiService.Sync) call.
527///
528/// # Activities
529///
530/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
531/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
532///
533/// * [sync devices](DeviceSyncCall) (request)
534#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
535#[serde_with::serde_as]
536#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
537pub struct SyncRequest {
538 /// Required. Third-party user ID.
539 #[serde(rename = "agentUserId")]
540 pub agent_user_id: Option<String>,
541 /// Request ID used for debugging.
542 #[serde(rename = "requestId")]
543 pub request_id: Option<String>,
544}
545
546impl common::RequestValue for SyncRequest {}
547
548/// Response type for the [`Sync`](#google.home.graph.v1.HomeGraphApiService.Sync) call. This should follow the same format as the Google smart home `action.devices.SYNC` [response](https://developers.home.google.com/cloud-to-cloud/intents/sync). Example: `json { "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf", "payload": { "agentUserId": "1836.15267389", "devices": [{ "id": "123", "type": "action.devices.types.OUTLET", "traits": [ "action.devices.traits.OnOff" ], "name": { "defaultNames": ["My Outlet 1234"], "name": "Night light", "nicknames": ["wall plug"] }, "willReportState": false, "deviceInfo": { "manufacturer": "lights-out-inc", "model": "hs1234", "hwVersion": "3.2", "swVersion": "11.4" }, "customData": { "fooValue": 74, "barValue": true, "bazValue": "foo" } }] } } `
549///
550/// # Activities
551///
552/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
553/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
554///
555/// * [sync devices](DeviceSyncCall) (response)
556#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
557#[serde_with::serde_as]
558#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
559pub struct SyncResponse {
560 /// Devices associated with the third-party user.
561 pub payload: Option<SyncResponsePayload>,
562 /// Request ID used for debugging. Copied from the request.
563 #[serde(rename = "requestId")]
564 pub request_id: Option<String>,
565}
566
567impl common::ResponseResult for SyncResponse {}
568
569/// Payload containing device information.
570///
571/// This type is not used in any activity, and only used as *part* of another schema.
572///
573#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
574#[serde_with::serde_as]
575#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
576pub struct SyncResponsePayload {
577 /// Third-party user ID
578 #[serde(rename = "agentUserId")]
579 pub agent_user_id: Option<String>,
580 /// Devices associated with the third-party user.
581 pub devices: Option<Vec<Device>>,
582}
583
584impl common::Part for SyncResponsePayload {}
585
586// ###################
587// MethodBuilders ###
588// #################
589
590/// A builder providing access to all methods supported on *agentUser* resources.
591/// It is not used directly, but through the [`HomeGraphService`] hub.
592///
593/// # Example
594///
595/// Instantiate a resource builder
596///
597/// ```test_harness,no_run
598/// extern crate hyper;
599/// extern crate hyper_rustls;
600/// extern crate google_homegraph1 as homegraph1;
601///
602/// # async fn dox() {
603/// use homegraph1::{HomeGraphService, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
604///
605/// let secret: yup_oauth2::ApplicationSecret = Default::default();
606/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
607/// .with_native_roots()
608/// .unwrap()
609/// .https_only()
610/// .enable_http2()
611/// .build();
612///
613/// let executor = hyper_util::rt::TokioExecutor::new();
614/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
615/// secret,
616/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
617/// yup_oauth2::client::CustomHyperClientBuilder::from(
618/// hyper_util::client::legacy::Client::builder(executor).build(connector),
619/// ),
620/// ).build().await.unwrap();
621///
622/// let client = hyper_util::client::legacy::Client::builder(
623/// hyper_util::rt::TokioExecutor::new()
624/// )
625/// .build(
626/// hyper_rustls::HttpsConnectorBuilder::new()
627/// .with_native_roots()
628/// .unwrap()
629/// .https_or_http()
630/// .enable_http2()
631/// .build()
632/// );
633/// let mut hub = HomeGraphService::new(client, auth);
634/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
635/// // like `delete(...)`
636/// // to build up your call.
637/// let rb = hub.agent_users();
638/// # }
639/// ```
640pub struct AgentUserMethods<'a, C>
641where
642 C: 'a,
643{
644 hub: &'a HomeGraphService<C>,
645}
646
647impl<'a, C> common::MethodsBuilder for AgentUserMethods<'a, C> {}
648
649impl<'a, C> AgentUserMethods<'a, C> {
650 /// Create a builder to help you perform the following task:
651 ///
652 /// Unlinks the given third-party user from your smart home Action. All data related to this user will be deleted. For more details on how users link their accounts, see [fulfillment and authentication](https://developers.home.google.com/cloud-to-cloud/primer/fulfillment). The third-party user's identity is passed in via the `agent_user_id` (see DeleteAgentUserRequest). This request must be authorized using service account credentials from your Actions console project.
653 ///
654 /// # Arguments
655 ///
656 /// * `agentUserId` - Required. Third-party user ID.
657 pub fn delete(&self, agent_user_id: &str) -> AgentUserDeleteCall<'a, C> {
658 AgentUserDeleteCall {
659 hub: self.hub,
660 _agent_user_id: agent_user_id.to_string(),
661 _request_id: Default::default(),
662 _delegate: Default::default(),
663 _additional_params: Default::default(),
664 _scopes: Default::default(),
665 }
666 }
667}
668
669/// A builder providing access to all methods supported on *device* resources.
670/// It is not used directly, but through the [`HomeGraphService`] hub.
671///
672/// # Example
673///
674/// Instantiate a resource builder
675///
676/// ```test_harness,no_run
677/// extern crate hyper;
678/// extern crate hyper_rustls;
679/// extern crate google_homegraph1 as homegraph1;
680///
681/// # async fn dox() {
682/// use homegraph1::{HomeGraphService, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
683///
684/// let secret: yup_oauth2::ApplicationSecret = Default::default();
685/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
686/// .with_native_roots()
687/// .unwrap()
688/// .https_only()
689/// .enable_http2()
690/// .build();
691///
692/// let executor = hyper_util::rt::TokioExecutor::new();
693/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
694/// secret,
695/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
696/// yup_oauth2::client::CustomHyperClientBuilder::from(
697/// hyper_util::client::legacy::Client::builder(executor).build(connector),
698/// ),
699/// ).build().await.unwrap();
700///
701/// let client = hyper_util::client::legacy::Client::builder(
702/// hyper_util::rt::TokioExecutor::new()
703/// )
704/// .build(
705/// hyper_rustls::HttpsConnectorBuilder::new()
706/// .with_native_roots()
707/// .unwrap()
708/// .https_or_http()
709/// .enable_http2()
710/// .build()
711/// );
712/// let mut hub = HomeGraphService::new(client, auth);
713/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
714/// // like `query(...)`, `report_state_and_notification(...)`, `request_sync(...)` and `sync(...)`
715/// // to build up your call.
716/// let rb = hub.devices();
717/// # }
718/// ```
719pub struct DeviceMethods<'a, C>
720where
721 C: 'a,
722{
723 hub: &'a HomeGraphService<C>,
724}
725
726impl<'a, C> common::MethodsBuilder for DeviceMethods<'a, C> {}
727
728impl<'a, C> DeviceMethods<'a, C> {
729 /// Create a builder to help you perform the following task:
730 ///
731 /// Gets the current states in Home Graph for the given set of the third-party user's devices. The third-party user's identity is passed in via the `agent_user_id` (see QueryRequest). This request must be authorized using service account credentials from your Actions console project.
732 ///
733 /// # Arguments
734 ///
735 /// * `request` - No description provided.
736 pub fn query(&self, request: QueryRequest) -> DeviceQueryCall<'a, C> {
737 DeviceQueryCall {
738 hub: self.hub,
739 _request: request,
740 _delegate: Default::default(),
741 _additional_params: Default::default(),
742 _scopes: Default::default(),
743 }
744 }
745
746 /// Create a builder to help you perform the following task:
747 ///
748 /// Reports device state and optionally sends device notifications. Called by your smart home Action when the state of a third-party device changes or you need to send a notification about the device. See [Implement Report State](https://developers.home.google.com/cloud-to-cloud/integration/report-state) for more information. This method updates the device state according to its declared [traits](https://developers.home.google.com/cloud-to-cloud/primer/device-types-and-traits). Publishing a new state value outside of these traits will result in an `INVALID_ARGUMENT` error response. The third-party user's identity is passed in via the `agent_user_id` (see ReportStateAndNotificationRequest). This request must be authorized using service account credentials from your Actions console project.
749 ///
750 /// # Arguments
751 ///
752 /// * `request` - No description provided.
753 pub fn report_state_and_notification(
754 &self,
755 request: ReportStateAndNotificationRequest,
756 ) -> DeviceReportStateAndNotificationCall<'a, C> {
757 DeviceReportStateAndNotificationCall {
758 hub: self.hub,
759 _request: request,
760 _delegate: Default::default(),
761 _additional_params: Default::default(),
762 _scopes: Default::default(),
763 }
764 }
765
766 /// Create a builder to help you perform the following task:
767 ///
768 /// Requests Google to send an `action.devices.SYNC` [intent](https://developers.home.google.com/cloud-to-cloud/intents/sync) to your smart home Action to update device metadata for the given user. The third-party user's identity is passed via the `agent_user_id` (see RequestSyncDevicesRequest). This request must be authorized using service account credentials from your Actions console project.
769 ///
770 /// # Arguments
771 ///
772 /// * `request` - No description provided.
773 pub fn request_sync(&self, request: RequestSyncDevicesRequest) -> DeviceRequestSyncCall<'a, C> {
774 DeviceRequestSyncCall {
775 hub: self.hub,
776 _request: request,
777 _delegate: Default::default(),
778 _additional_params: Default::default(),
779 _scopes: Default::default(),
780 }
781 }
782
783 /// Create a builder to help you perform the following task:
784 ///
785 /// Gets all the devices associated with the given third-party user. The third-party user's identity is passed in via the `agent_user_id` (see SyncRequest). This request must be authorized using service account credentials from your Actions console project.
786 ///
787 /// # Arguments
788 ///
789 /// * `request` - No description provided.
790 pub fn sync(&self, request: SyncRequest) -> DeviceSyncCall<'a, C> {
791 DeviceSyncCall {
792 hub: self.hub,
793 _request: request,
794 _delegate: Default::default(),
795 _additional_params: Default::default(),
796 _scopes: Default::default(),
797 }
798 }
799}
800
801// ###################
802// CallBuilders ###
803// #################
804
805/// Unlinks the given third-party user from your smart home Action. All data related to this user will be deleted. For more details on how users link their accounts, see [fulfillment and authentication](https://developers.home.google.com/cloud-to-cloud/primer/fulfillment). The third-party user's identity is passed in via the `agent_user_id` (see DeleteAgentUserRequest). This request must be authorized using service account credentials from your Actions console project.
806///
807/// A builder for the *delete* method supported by a *agentUser* resource.
808/// It is not used directly, but through a [`AgentUserMethods`] instance.
809///
810/// # Example
811///
812/// Instantiate a resource method builder
813///
814/// ```test_harness,no_run
815/// # extern crate hyper;
816/// # extern crate hyper_rustls;
817/// # extern crate google_homegraph1 as homegraph1;
818/// # async fn dox() {
819/// # use homegraph1::{HomeGraphService, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
820///
821/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
822/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
823/// # .with_native_roots()
824/// # .unwrap()
825/// # .https_only()
826/// # .enable_http2()
827/// # .build();
828///
829/// # let executor = hyper_util::rt::TokioExecutor::new();
830/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
831/// # secret,
832/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
833/// # yup_oauth2::client::CustomHyperClientBuilder::from(
834/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
835/// # ),
836/// # ).build().await.unwrap();
837///
838/// # let client = hyper_util::client::legacy::Client::builder(
839/// # hyper_util::rt::TokioExecutor::new()
840/// # )
841/// # .build(
842/// # hyper_rustls::HttpsConnectorBuilder::new()
843/// # .with_native_roots()
844/// # .unwrap()
845/// # .https_or_http()
846/// # .enable_http2()
847/// # .build()
848/// # );
849/// # let mut hub = HomeGraphService::new(client, auth);
850/// // You can configure optional parameters by calling the respective setters at will, and
851/// // execute the final call using `doit()`.
852/// // Values shown here are possibly random and not representative !
853/// let result = hub.agent_users().delete("agentUserId")
854/// .request_id("magna")
855/// .doit().await;
856/// # }
857/// ```
858pub struct AgentUserDeleteCall<'a, C>
859where
860 C: 'a,
861{
862 hub: &'a HomeGraphService<C>,
863 _agent_user_id: String,
864 _request_id: Option<String>,
865 _delegate: Option<&'a mut dyn common::Delegate>,
866 _additional_params: HashMap<String, String>,
867 _scopes: BTreeSet<String>,
868}
869
870impl<'a, C> common::CallBuilder for AgentUserDeleteCall<'a, C> {}
871
872impl<'a, C> AgentUserDeleteCall<'a, C>
873where
874 C: common::Connector,
875{
876 /// Perform the operation you have build so far.
877 pub async fn doit(mut self) -> common::Result<(common::Response, Empty)> {
878 use std::borrow::Cow;
879 use std::io::{Read, Seek};
880
881 use common::{url::Params, ToParts};
882 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
883
884 let mut dd = common::DefaultDelegate;
885 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
886 dlg.begin(common::MethodInfo {
887 id: "homegraph.agentUsers.delete",
888 http_method: hyper::Method::DELETE,
889 });
890
891 for &field in ["alt", "agentUserId", "requestId"].iter() {
892 if self._additional_params.contains_key(field) {
893 dlg.finished(false);
894 return Err(common::Error::FieldClash(field));
895 }
896 }
897
898 let mut params = Params::with_capacity(4 + self._additional_params.len());
899 params.push("agentUserId", self._agent_user_id);
900 if let Some(value) = self._request_id.as_ref() {
901 params.push("requestId", value);
902 }
903
904 params.extend(self._additional_params.iter());
905
906 params.push("alt", "json");
907 let mut url = self.hub._base_url.clone() + "v1/{+agentUserId}";
908 if self._scopes.is_empty() {
909 self._scopes.insert(Scope::Full.as_ref().to_string());
910 }
911
912 #[allow(clippy::single_element_loop)]
913 for &(find_this, param_name) in [("{+agentUserId}", "agentUserId")].iter() {
914 url = params.uri_replacement(url, param_name, find_this, true);
915 }
916 {
917 let to_remove = ["agentUserId"];
918 params.remove_params(&to_remove);
919 }
920
921 let url = params.parse_with_url(&url);
922
923 loop {
924 let token = match self
925 .hub
926 .auth
927 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
928 .await
929 {
930 Ok(token) => token,
931 Err(e) => match dlg.token(e) {
932 Ok(token) => token,
933 Err(e) => {
934 dlg.finished(false);
935 return Err(common::Error::MissingToken(e));
936 }
937 },
938 };
939 let mut req_result = {
940 let client = &self.hub.client;
941 dlg.pre_request();
942 let mut req_builder = hyper::Request::builder()
943 .method(hyper::Method::DELETE)
944 .uri(url.as_str())
945 .header(USER_AGENT, self.hub._user_agent.clone());
946
947 if let Some(token) = token.as_ref() {
948 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
949 }
950
951 let request = req_builder
952 .header(CONTENT_LENGTH, 0_u64)
953 .body(common::to_body::<String>(None));
954
955 client.request(request.unwrap()).await
956 };
957
958 match req_result {
959 Err(err) => {
960 if let common::Retry::After(d) = dlg.http_error(&err) {
961 sleep(d).await;
962 continue;
963 }
964 dlg.finished(false);
965 return Err(common::Error::HttpError(err));
966 }
967 Ok(res) => {
968 let (mut parts, body) = res.into_parts();
969 let mut body = common::Body::new(body);
970 if !parts.status.is_success() {
971 let bytes = common::to_bytes(body).await.unwrap_or_default();
972 let error = serde_json::from_str(&common::to_string(&bytes));
973 let response = common::to_response(parts, bytes.into());
974
975 if let common::Retry::After(d) =
976 dlg.http_failure(&response, error.as_ref().ok())
977 {
978 sleep(d).await;
979 continue;
980 }
981
982 dlg.finished(false);
983
984 return Err(match error {
985 Ok(value) => common::Error::BadRequest(value),
986 _ => common::Error::Failure(response),
987 });
988 }
989 let response = {
990 let bytes = common::to_bytes(body).await.unwrap_or_default();
991 let encoded = common::to_string(&bytes);
992 match serde_json::from_str(&encoded) {
993 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
994 Err(error) => {
995 dlg.response_json_decode_error(&encoded, &error);
996 return Err(common::Error::JsonDecodeError(
997 encoded.to_string(),
998 error,
999 ));
1000 }
1001 }
1002 };
1003
1004 dlg.finished(true);
1005 return Ok(response);
1006 }
1007 }
1008 }
1009 }
1010
1011 /// Required. Third-party user ID.
1012 ///
1013 /// Sets the *agent user id* path property to the given value.
1014 ///
1015 /// Even though the property as already been set when instantiating this call,
1016 /// we provide this method for API completeness.
1017 pub fn agent_user_id(mut self, new_value: &str) -> AgentUserDeleteCall<'a, C> {
1018 self._agent_user_id = new_value.to_string();
1019 self
1020 }
1021 /// Request ID used for debugging.
1022 ///
1023 /// Sets the *request id* query property to the given value.
1024 pub fn request_id(mut self, new_value: &str) -> AgentUserDeleteCall<'a, C> {
1025 self._request_id = Some(new_value.to_string());
1026 self
1027 }
1028 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1029 /// while executing the actual API request.
1030 ///
1031 /// ````text
1032 /// It should be used to handle progress information, and to implement a certain level of resilience.
1033 /// ````
1034 ///
1035 /// Sets the *delegate* property to the given value.
1036 pub fn delegate(
1037 mut self,
1038 new_value: &'a mut dyn common::Delegate,
1039 ) -> AgentUserDeleteCall<'a, C> {
1040 self._delegate = Some(new_value);
1041 self
1042 }
1043
1044 /// Set any additional parameter of the query string used in the request.
1045 /// It should be used to set parameters which are not yet available through their own
1046 /// setters.
1047 ///
1048 /// Please note that this method must not be used to set any of the known parameters
1049 /// which have their own setter method. If done anyway, the request will fail.
1050 ///
1051 /// # Additional Parameters
1052 ///
1053 /// * *$.xgafv* (query-string) - V1 error format.
1054 /// * *access_token* (query-string) - OAuth access token.
1055 /// * *alt* (query-string) - Data format for response.
1056 /// * *callback* (query-string) - JSONP
1057 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1058 /// * *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.
1059 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1060 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1061 /// * *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.
1062 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1063 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1064 pub fn param<T>(mut self, name: T, value: T) -> AgentUserDeleteCall<'a, C>
1065 where
1066 T: AsRef<str>,
1067 {
1068 self._additional_params
1069 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1070 self
1071 }
1072
1073 /// Identifies the authorization scope for the method you are building.
1074 ///
1075 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1076 /// [`Scope::Full`].
1077 ///
1078 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1079 /// tokens for more than one scope.
1080 ///
1081 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1082 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1083 /// sufficient, a read-write scope will do as well.
1084 pub fn add_scope<St>(mut self, scope: St) -> AgentUserDeleteCall<'a, C>
1085 where
1086 St: AsRef<str>,
1087 {
1088 self._scopes.insert(String::from(scope.as_ref()));
1089 self
1090 }
1091 /// Identifies the authorization scope(s) for the method you are building.
1092 ///
1093 /// See [`Self::add_scope()`] for details.
1094 pub fn add_scopes<I, St>(mut self, scopes: I) -> AgentUserDeleteCall<'a, C>
1095 where
1096 I: IntoIterator<Item = St>,
1097 St: AsRef<str>,
1098 {
1099 self._scopes
1100 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1101 self
1102 }
1103
1104 /// Removes all scopes, and no default scope will be used either.
1105 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1106 /// for details).
1107 pub fn clear_scopes(mut self) -> AgentUserDeleteCall<'a, C> {
1108 self._scopes.clear();
1109 self
1110 }
1111}
1112
1113/// Gets the current states in Home Graph for the given set of the third-party user's devices. The third-party user's identity is passed in via the `agent_user_id` (see QueryRequest). This request must be authorized using service account credentials from your Actions console project.
1114///
1115/// A builder for the *query* method supported by a *device* resource.
1116/// It is not used directly, but through a [`DeviceMethods`] instance.
1117///
1118/// # Example
1119///
1120/// Instantiate a resource method builder
1121///
1122/// ```test_harness,no_run
1123/// # extern crate hyper;
1124/// # extern crate hyper_rustls;
1125/// # extern crate google_homegraph1 as homegraph1;
1126/// use homegraph1::api::QueryRequest;
1127/// # async fn dox() {
1128/// # use homegraph1::{HomeGraphService, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1129///
1130/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1131/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1132/// # .with_native_roots()
1133/// # .unwrap()
1134/// # .https_only()
1135/// # .enable_http2()
1136/// # .build();
1137///
1138/// # let executor = hyper_util::rt::TokioExecutor::new();
1139/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1140/// # secret,
1141/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1142/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1143/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1144/// # ),
1145/// # ).build().await.unwrap();
1146///
1147/// # let client = hyper_util::client::legacy::Client::builder(
1148/// # hyper_util::rt::TokioExecutor::new()
1149/// # )
1150/// # .build(
1151/// # hyper_rustls::HttpsConnectorBuilder::new()
1152/// # .with_native_roots()
1153/// # .unwrap()
1154/// # .https_or_http()
1155/// # .enable_http2()
1156/// # .build()
1157/// # );
1158/// # let mut hub = HomeGraphService::new(client, auth);
1159/// // As the method needs a request, you would usually fill it with the desired information
1160/// // into the respective structure. Some of the parts shown here might not be applicable !
1161/// // Values shown here are possibly random and not representative !
1162/// let mut req = QueryRequest::default();
1163///
1164/// // You can configure optional parameters by calling the respective setters at will, and
1165/// // execute the final call using `doit()`.
1166/// // Values shown here are possibly random and not representative !
1167/// let result = hub.devices().query(req)
1168/// .doit().await;
1169/// # }
1170/// ```
1171pub struct DeviceQueryCall<'a, C>
1172where
1173 C: 'a,
1174{
1175 hub: &'a HomeGraphService<C>,
1176 _request: QueryRequest,
1177 _delegate: Option<&'a mut dyn common::Delegate>,
1178 _additional_params: HashMap<String, String>,
1179 _scopes: BTreeSet<String>,
1180}
1181
1182impl<'a, C> common::CallBuilder for DeviceQueryCall<'a, C> {}
1183
1184impl<'a, C> DeviceQueryCall<'a, C>
1185where
1186 C: common::Connector,
1187{
1188 /// Perform the operation you have build so far.
1189 pub async fn doit(mut self) -> common::Result<(common::Response, QueryResponse)> {
1190 use std::borrow::Cow;
1191 use std::io::{Read, Seek};
1192
1193 use common::{url::Params, ToParts};
1194 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1195
1196 let mut dd = common::DefaultDelegate;
1197 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1198 dlg.begin(common::MethodInfo {
1199 id: "homegraph.devices.query",
1200 http_method: hyper::Method::POST,
1201 });
1202
1203 for &field in ["alt"].iter() {
1204 if self._additional_params.contains_key(field) {
1205 dlg.finished(false);
1206 return Err(common::Error::FieldClash(field));
1207 }
1208 }
1209
1210 let mut params = Params::with_capacity(3 + self._additional_params.len());
1211
1212 params.extend(self._additional_params.iter());
1213
1214 params.push("alt", "json");
1215 let mut url = self.hub._base_url.clone() + "v1/devices:query";
1216 if self._scopes.is_empty() {
1217 self._scopes.insert(Scope::Full.as_ref().to_string());
1218 }
1219
1220 let url = params.parse_with_url(&url);
1221
1222 let mut json_mime_type = mime::APPLICATION_JSON;
1223 let mut request_value_reader = {
1224 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1225 common::remove_json_null_values(&mut value);
1226 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1227 serde_json::to_writer(&mut dst, &value).unwrap();
1228 dst
1229 };
1230 let request_size = request_value_reader
1231 .seek(std::io::SeekFrom::End(0))
1232 .unwrap();
1233 request_value_reader
1234 .seek(std::io::SeekFrom::Start(0))
1235 .unwrap();
1236
1237 loop {
1238 let token = match self
1239 .hub
1240 .auth
1241 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1242 .await
1243 {
1244 Ok(token) => token,
1245 Err(e) => match dlg.token(e) {
1246 Ok(token) => token,
1247 Err(e) => {
1248 dlg.finished(false);
1249 return Err(common::Error::MissingToken(e));
1250 }
1251 },
1252 };
1253 request_value_reader
1254 .seek(std::io::SeekFrom::Start(0))
1255 .unwrap();
1256 let mut req_result = {
1257 let client = &self.hub.client;
1258 dlg.pre_request();
1259 let mut req_builder = hyper::Request::builder()
1260 .method(hyper::Method::POST)
1261 .uri(url.as_str())
1262 .header(USER_AGENT, self.hub._user_agent.clone());
1263
1264 if let Some(token) = token.as_ref() {
1265 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1266 }
1267
1268 let request = req_builder
1269 .header(CONTENT_TYPE, json_mime_type.to_string())
1270 .header(CONTENT_LENGTH, request_size as u64)
1271 .body(common::to_body(
1272 request_value_reader.get_ref().clone().into(),
1273 ));
1274
1275 client.request(request.unwrap()).await
1276 };
1277
1278 match req_result {
1279 Err(err) => {
1280 if let common::Retry::After(d) = dlg.http_error(&err) {
1281 sleep(d).await;
1282 continue;
1283 }
1284 dlg.finished(false);
1285 return Err(common::Error::HttpError(err));
1286 }
1287 Ok(res) => {
1288 let (mut parts, body) = res.into_parts();
1289 let mut body = common::Body::new(body);
1290 if !parts.status.is_success() {
1291 let bytes = common::to_bytes(body).await.unwrap_or_default();
1292 let error = serde_json::from_str(&common::to_string(&bytes));
1293 let response = common::to_response(parts, bytes.into());
1294
1295 if let common::Retry::After(d) =
1296 dlg.http_failure(&response, error.as_ref().ok())
1297 {
1298 sleep(d).await;
1299 continue;
1300 }
1301
1302 dlg.finished(false);
1303
1304 return Err(match error {
1305 Ok(value) => common::Error::BadRequest(value),
1306 _ => common::Error::Failure(response),
1307 });
1308 }
1309 let response = {
1310 let bytes = common::to_bytes(body).await.unwrap_or_default();
1311 let encoded = common::to_string(&bytes);
1312 match serde_json::from_str(&encoded) {
1313 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1314 Err(error) => {
1315 dlg.response_json_decode_error(&encoded, &error);
1316 return Err(common::Error::JsonDecodeError(
1317 encoded.to_string(),
1318 error,
1319 ));
1320 }
1321 }
1322 };
1323
1324 dlg.finished(true);
1325 return Ok(response);
1326 }
1327 }
1328 }
1329 }
1330
1331 ///
1332 /// Sets the *request* property to the given value.
1333 ///
1334 /// Even though the property as already been set when instantiating this call,
1335 /// we provide this method for API completeness.
1336 pub fn request(mut self, new_value: QueryRequest) -> DeviceQueryCall<'a, C> {
1337 self._request = new_value;
1338 self
1339 }
1340 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1341 /// while executing the actual API request.
1342 ///
1343 /// ````text
1344 /// It should be used to handle progress information, and to implement a certain level of resilience.
1345 /// ````
1346 ///
1347 /// Sets the *delegate* property to the given value.
1348 pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> DeviceQueryCall<'a, C> {
1349 self._delegate = Some(new_value);
1350 self
1351 }
1352
1353 /// Set any additional parameter of the query string used in the request.
1354 /// It should be used to set parameters which are not yet available through their own
1355 /// setters.
1356 ///
1357 /// Please note that this method must not be used to set any of the known parameters
1358 /// which have their own setter method. If done anyway, the request will fail.
1359 ///
1360 /// # Additional Parameters
1361 ///
1362 /// * *$.xgafv* (query-string) - V1 error format.
1363 /// * *access_token* (query-string) - OAuth access token.
1364 /// * *alt* (query-string) - Data format for response.
1365 /// * *callback* (query-string) - JSONP
1366 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1367 /// * *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.
1368 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1369 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1370 /// * *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.
1371 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1372 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1373 pub fn param<T>(mut self, name: T, value: T) -> DeviceQueryCall<'a, C>
1374 where
1375 T: AsRef<str>,
1376 {
1377 self._additional_params
1378 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1379 self
1380 }
1381
1382 /// Identifies the authorization scope for the method you are building.
1383 ///
1384 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1385 /// [`Scope::Full`].
1386 ///
1387 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1388 /// tokens for more than one scope.
1389 ///
1390 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1391 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1392 /// sufficient, a read-write scope will do as well.
1393 pub fn add_scope<St>(mut self, scope: St) -> DeviceQueryCall<'a, C>
1394 where
1395 St: AsRef<str>,
1396 {
1397 self._scopes.insert(String::from(scope.as_ref()));
1398 self
1399 }
1400 /// Identifies the authorization scope(s) for the method you are building.
1401 ///
1402 /// See [`Self::add_scope()`] for details.
1403 pub fn add_scopes<I, St>(mut self, scopes: I) -> DeviceQueryCall<'a, C>
1404 where
1405 I: IntoIterator<Item = St>,
1406 St: AsRef<str>,
1407 {
1408 self._scopes
1409 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1410 self
1411 }
1412
1413 /// Removes all scopes, and no default scope will be used either.
1414 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1415 /// for details).
1416 pub fn clear_scopes(mut self) -> DeviceQueryCall<'a, C> {
1417 self._scopes.clear();
1418 self
1419 }
1420}
1421
1422/// Reports device state and optionally sends device notifications. Called by your smart home Action when the state of a third-party device changes or you need to send a notification about the device. See [Implement Report State](https://developers.home.google.com/cloud-to-cloud/integration/report-state) for more information. This method updates the device state according to its declared [traits](https://developers.home.google.com/cloud-to-cloud/primer/device-types-and-traits). Publishing a new state value outside of these traits will result in an `INVALID_ARGUMENT` error response. The third-party user's identity is passed in via the `agent_user_id` (see ReportStateAndNotificationRequest). This request must be authorized using service account credentials from your Actions console project.
1423///
1424/// A builder for the *reportStateAndNotification* method supported by a *device* resource.
1425/// It is not used directly, but through a [`DeviceMethods`] instance.
1426///
1427/// # Example
1428///
1429/// Instantiate a resource method builder
1430///
1431/// ```test_harness,no_run
1432/// # extern crate hyper;
1433/// # extern crate hyper_rustls;
1434/// # extern crate google_homegraph1 as homegraph1;
1435/// use homegraph1::api::ReportStateAndNotificationRequest;
1436/// # async fn dox() {
1437/// # use homegraph1::{HomeGraphService, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1438///
1439/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1440/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1441/// # .with_native_roots()
1442/// # .unwrap()
1443/// # .https_only()
1444/// # .enable_http2()
1445/// # .build();
1446///
1447/// # let executor = hyper_util::rt::TokioExecutor::new();
1448/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1449/// # secret,
1450/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1451/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1452/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1453/// # ),
1454/// # ).build().await.unwrap();
1455///
1456/// # let client = hyper_util::client::legacy::Client::builder(
1457/// # hyper_util::rt::TokioExecutor::new()
1458/// # )
1459/// # .build(
1460/// # hyper_rustls::HttpsConnectorBuilder::new()
1461/// # .with_native_roots()
1462/// # .unwrap()
1463/// # .https_or_http()
1464/// # .enable_http2()
1465/// # .build()
1466/// # );
1467/// # let mut hub = HomeGraphService::new(client, auth);
1468/// // As the method needs a request, you would usually fill it with the desired information
1469/// // into the respective structure. Some of the parts shown here might not be applicable !
1470/// // Values shown here are possibly random and not representative !
1471/// let mut req = ReportStateAndNotificationRequest::default();
1472///
1473/// // You can configure optional parameters by calling the respective setters at will, and
1474/// // execute the final call using `doit()`.
1475/// // Values shown here are possibly random and not representative !
1476/// let result = hub.devices().report_state_and_notification(req)
1477/// .doit().await;
1478/// # }
1479/// ```
1480pub struct DeviceReportStateAndNotificationCall<'a, C>
1481where
1482 C: 'a,
1483{
1484 hub: &'a HomeGraphService<C>,
1485 _request: ReportStateAndNotificationRequest,
1486 _delegate: Option<&'a mut dyn common::Delegate>,
1487 _additional_params: HashMap<String, String>,
1488 _scopes: BTreeSet<String>,
1489}
1490
1491impl<'a, C> common::CallBuilder for DeviceReportStateAndNotificationCall<'a, C> {}
1492
1493impl<'a, C> DeviceReportStateAndNotificationCall<'a, C>
1494where
1495 C: common::Connector,
1496{
1497 /// Perform the operation you have build so far.
1498 pub async fn doit(
1499 mut self,
1500 ) -> common::Result<(common::Response, ReportStateAndNotificationResponse)> {
1501 use std::borrow::Cow;
1502 use std::io::{Read, Seek};
1503
1504 use common::{url::Params, ToParts};
1505 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1506
1507 let mut dd = common::DefaultDelegate;
1508 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1509 dlg.begin(common::MethodInfo {
1510 id: "homegraph.devices.reportStateAndNotification",
1511 http_method: hyper::Method::POST,
1512 });
1513
1514 for &field in ["alt"].iter() {
1515 if self._additional_params.contains_key(field) {
1516 dlg.finished(false);
1517 return Err(common::Error::FieldClash(field));
1518 }
1519 }
1520
1521 let mut params = Params::with_capacity(3 + self._additional_params.len());
1522
1523 params.extend(self._additional_params.iter());
1524
1525 params.push("alt", "json");
1526 let mut url = self.hub._base_url.clone() + "v1/devices:reportStateAndNotification";
1527 if self._scopes.is_empty() {
1528 self._scopes.insert(Scope::Full.as_ref().to_string());
1529 }
1530
1531 let url = params.parse_with_url(&url);
1532
1533 let mut json_mime_type = mime::APPLICATION_JSON;
1534 let mut request_value_reader = {
1535 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1536 common::remove_json_null_values(&mut value);
1537 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1538 serde_json::to_writer(&mut dst, &value).unwrap();
1539 dst
1540 };
1541 let request_size = request_value_reader
1542 .seek(std::io::SeekFrom::End(0))
1543 .unwrap();
1544 request_value_reader
1545 .seek(std::io::SeekFrom::Start(0))
1546 .unwrap();
1547
1548 loop {
1549 let token = match self
1550 .hub
1551 .auth
1552 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1553 .await
1554 {
1555 Ok(token) => token,
1556 Err(e) => match dlg.token(e) {
1557 Ok(token) => token,
1558 Err(e) => {
1559 dlg.finished(false);
1560 return Err(common::Error::MissingToken(e));
1561 }
1562 },
1563 };
1564 request_value_reader
1565 .seek(std::io::SeekFrom::Start(0))
1566 .unwrap();
1567 let mut req_result = {
1568 let client = &self.hub.client;
1569 dlg.pre_request();
1570 let mut req_builder = hyper::Request::builder()
1571 .method(hyper::Method::POST)
1572 .uri(url.as_str())
1573 .header(USER_AGENT, self.hub._user_agent.clone());
1574
1575 if let Some(token) = token.as_ref() {
1576 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1577 }
1578
1579 let request = req_builder
1580 .header(CONTENT_TYPE, json_mime_type.to_string())
1581 .header(CONTENT_LENGTH, request_size as u64)
1582 .body(common::to_body(
1583 request_value_reader.get_ref().clone().into(),
1584 ));
1585
1586 client.request(request.unwrap()).await
1587 };
1588
1589 match req_result {
1590 Err(err) => {
1591 if let common::Retry::After(d) = dlg.http_error(&err) {
1592 sleep(d).await;
1593 continue;
1594 }
1595 dlg.finished(false);
1596 return Err(common::Error::HttpError(err));
1597 }
1598 Ok(res) => {
1599 let (mut parts, body) = res.into_parts();
1600 let mut body = common::Body::new(body);
1601 if !parts.status.is_success() {
1602 let bytes = common::to_bytes(body).await.unwrap_or_default();
1603 let error = serde_json::from_str(&common::to_string(&bytes));
1604 let response = common::to_response(parts, bytes.into());
1605
1606 if let common::Retry::After(d) =
1607 dlg.http_failure(&response, error.as_ref().ok())
1608 {
1609 sleep(d).await;
1610 continue;
1611 }
1612
1613 dlg.finished(false);
1614
1615 return Err(match error {
1616 Ok(value) => common::Error::BadRequest(value),
1617 _ => common::Error::Failure(response),
1618 });
1619 }
1620 let response = {
1621 let bytes = common::to_bytes(body).await.unwrap_or_default();
1622 let encoded = common::to_string(&bytes);
1623 match serde_json::from_str(&encoded) {
1624 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1625 Err(error) => {
1626 dlg.response_json_decode_error(&encoded, &error);
1627 return Err(common::Error::JsonDecodeError(
1628 encoded.to_string(),
1629 error,
1630 ));
1631 }
1632 }
1633 };
1634
1635 dlg.finished(true);
1636 return Ok(response);
1637 }
1638 }
1639 }
1640 }
1641
1642 ///
1643 /// Sets the *request* property to the given value.
1644 ///
1645 /// Even though the property as already been set when instantiating this call,
1646 /// we provide this method for API completeness.
1647 pub fn request(
1648 mut self,
1649 new_value: ReportStateAndNotificationRequest,
1650 ) -> DeviceReportStateAndNotificationCall<'a, C> {
1651 self._request = new_value;
1652 self
1653 }
1654 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1655 /// while executing the actual API request.
1656 ///
1657 /// ````text
1658 /// It should be used to handle progress information, and to implement a certain level of resilience.
1659 /// ````
1660 ///
1661 /// Sets the *delegate* property to the given value.
1662 pub fn delegate(
1663 mut self,
1664 new_value: &'a mut dyn common::Delegate,
1665 ) -> DeviceReportStateAndNotificationCall<'a, C> {
1666 self._delegate = Some(new_value);
1667 self
1668 }
1669
1670 /// Set any additional parameter of the query string used in the request.
1671 /// It should be used to set parameters which are not yet available through their own
1672 /// setters.
1673 ///
1674 /// Please note that this method must not be used to set any of the known parameters
1675 /// which have their own setter method. If done anyway, the request will fail.
1676 ///
1677 /// # Additional Parameters
1678 ///
1679 /// * *$.xgafv* (query-string) - V1 error format.
1680 /// * *access_token* (query-string) - OAuth access token.
1681 /// * *alt* (query-string) - Data format for response.
1682 /// * *callback* (query-string) - JSONP
1683 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1684 /// * *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.
1685 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1686 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1687 /// * *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.
1688 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1689 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1690 pub fn param<T>(mut self, name: T, value: T) -> DeviceReportStateAndNotificationCall<'a, C>
1691 where
1692 T: AsRef<str>,
1693 {
1694 self._additional_params
1695 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1696 self
1697 }
1698
1699 /// Identifies the authorization scope for the method you are building.
1700 ///
1701 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1702 /// [`Scope::Full`].
1703 ///
1704 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1705 /// tokens for more than one scope.
1706 ///
1707 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1708 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1709 /// sufficient, a read-write scope will do as well.
1710 pub fn add_scope<St>(mut self, scope: St) -> DeviceReportStateAndNotificationCall<'a, C>
1711 where
1712 St: AsRef<str>,
1713 {
1714 self._scopes.insert(String::from(scope.as_ref()));
1715 self
1716 }
1717 /// Identifies the authorization scope(s) for the method you are building.
1718 ///
1719 /// See [`Self::add_scope()`] for details.
1720 pub fn add_scopes<I, St>(mut self, scopes: I) -> DeviceReportStateAndNotificationCall<'a, C>
1721 where
1722 I: IntoIterator<Item = St>,
1723 St: AsRef<str>,
1724 {
1725 self._scopes
1726 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1727 self
1728 }
1729
1730 /// Removes all scopes, and no default scope will be used either.
1731 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1732 /// for details).
1733 pub fn clear_scopes(mut self) -> DeviceReportStateAndNotificationCall<'a, C> {
1734 self._scopes.clear();
1735 self
1736 }
1737}
1738
1739/// Requests Google to send an `action.devices.SYNC` [intent](https://developers.home.google.com/cloud-to-cloud/intents/sync) to your smart home Action to update device metadata for the given user. The third-party user's identity is passed via the `agent_user_id` (see RequestSyncDevicesRequest). This request must be authorized using service account credentials from your Actions console project.
1740///
1741/// A builder for the *requestSync* method supported by a *device* resource.
1742/// It is not used directly, but through a [`DeviceMethods`] instance.
1743///
1744/// # Example
1745///
1746/// Instantiate a resource method builder
1747///
1748/// ```test_harness,no_run
1749/// # extern crate hyper;
1750/// # extern crate hyper_rustls;
1751/// # extern crate google_homegraph1 as homegraph1;
1752/// use homegraph1::api::RequestSyncDevicesRequest;
1753/// # async fn dox() {
1754/// # use homegraph1::{HomeGraphService, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1755///
1756/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1757/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1758/// # .with_native_roots()
1759/// # .unwrap()
1760/// # .https_only()
1761/// # .enable_http2()
1762/// # .build();
1763///
1764/// # let executor = hyper_util::rt::TokioExecutor::new();
1765/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1766/// # secret,
1767/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1768/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1769/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1770/// # ),
1771/// # ).build().await.unwrap();
1772///
1773/// # let client = hyper_util::client::legacy::Client::builder(
1774/// # hyper_util::rt::TokioExecutor::new()
1775/// # )
1776/// # .build(
1777/// # hyper_rustls::HttpsConnectorBuilder::new()
1778/// # .with_native_roots()
1779/// # .unwrap()
1780/// # .https_or_http()
1781/// # .enable_http2()
1782/// # .build()
1783/// # );
1784/// # let mut hub = HomeGraphService::new(client, auth);
1785/// // As the method needs a request, you would usually fill it with the desired information
1786/// // into the respective structure. Some of the parts shown here might not be applicable !
1787/// // Values shown here are possibly random and not representative !
1788/// let mut req = RequestSyncDevicesRequest::default();
1789///
1790/// // You can configure optional parameters by calling the respective setters at will, and
1791/// // execute the final call using `doit()`.
1792/// // Values shown here are possibly random and not representative !
1793/// let result = hub.devices().request_sync(req)
1794/// .doit().await;
1795/// # }
1796/// ```
1797pub struct DeviceRequestSyncCall<'a, C>
1798where
1799 C: 'a,
1800{
1801 hub: &'a HomeGraphService<C>,
1802 _request: RequestSyncDevicesRequest,
1803 _delegate: Option<&'a mut dyn common::Delegate>,
1804 _additional_params: HashMap<String, String>,
1805 _scopes: BTreeSet<String>,
1806}
1807
1808impl<'a, C> common::CallBuilder for DeviceRequestSyncCall<'a, C> {}
1809
1810impl<'a, C> DeviceRequestSyncCall<'a, C>
1811where
1812 C: common::Connector,
1813{
1814 /// Perform the operation you have build so far.
1815 pub async fn doit(mut self) -> common::Result<(common::Response, RequestSyncDevicesResponse)> {
1816 use std::borrow::Cow;
1817 use std::io::{Read, Seek};
1818
1819 use common::{url::Params, ToParts};
1820 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1821
1822 let mut dd = common::DefaultDelegate;
1823 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1824 dlg.begin(common::MethodInfo {
1825 id: "homegraph.devices.requestSync",
1826 http_method: hyper::Method::POST,
1827 });
1828
1829 for &field in ["alt"].iter() {
1830 if self._additional_params.contains_key(field) {
1831 dlg.finished(false);
1832 return Err(common::Error::FieldClash(field));
1833 }
1834 }
1835
1836 let mut params = Params::with_capacity(3 + self._additional_params.len());
1837
1838 params.extend(self._additional_params.iter());
1839
1840 params.push("alt", "json");
1841 let mut url = self.hub._base_url.clone() + "v1/devices:requestSync";
1842 if self._scopes.is_empty() {
1843 self._scopes.insert(Scope::Full.as_ref().to_string());
1844 }
1845
1846 let url = params.parse_with_url(&url);
1847
1848 let mut json_mime_type = mime::APPLICATION_JSON;
1849 let mut request_value_reader = {
1850 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1851 common::remove_json_null_values(&mut value);
1852 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1853 serde_json::to_writer(&mut dst, &value).unwrap();
1854 dst
1855 };
1856 let request_size = request_value_reader
1857 .seek(std::io::SeekFrom::End(0))
1858 .unwrap();
1859 request_value_reader
1860 .seek(std::io::SeekFrom::Start(0))
1861 .unwrap();
1862
1863 loop {
1864 let token = match self
1865 .hub
1866 .auth
1867 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1868 .await
1869 {
1870 Ok(token) => token,
1871 Err(e) => match dlg.token(e) {
1872 Ok(token) => token,
1873 Err(e) => {
1874 dlg.finished(false);
1875 return Err(common::Error::MissingToken(e));
1876 }
1877 },
1878 };
1879 request_value_reader
1880 .seek(std::io::SeekFrom::Start(0))
1881 .unwrap();
1882 let mut req_result = {
1883 let client = &self.hub.client;
1884 dlg.pre_request();
1885 let mut req_builder = hyper::Request::builder()
1886 .method(hyper::Method::POST)
1887 .uri(url.as_str())
1888 .header(USER_AGENT, self.hub._user_agent.clone());
1889
1890 if let Some(token) = token.as_ref() {
1891 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1892 }
1893
1894 let request = req_builder
1895 .header(CONTENT_TYPE, json_mime_type.to_string())
1896 .header(CONTENT_LENGTH, request_size as u64)
1897 .body(common::to_body(
1898 request_value_reader.get_ref().clone().into(),
1899 ));
1900
1901 client.request(request.unwrap()).await
1902 };
1903
1904 match req_result {
1905 Err(err) => {
1906 if let common::Retry::After(d) = dlg.http_error(&err) {
1907 sleep(d).await;
1908 continue;
1909 }
1910 dlg.finished(false);
1911 return Err(common::Error::HttpError(err));
1912 }
1913 Ok(res) => {
1914 let (mut parts, body) = res.into_parts();
1915 let mut body = common::Body::new(body);
1916 if !parts.status.is_success() {
1917 let bytes = common::to_bytes(body).await.unwrap_or_default();
1918 let error = serde_json::from_str(&common::to_string(&bytes));
1919 let response = common::to_response(parts, bytes.into());
1920
1921 if let common::Retry::After(d) =
1922 dlg.http_failure(&response, error.as_ref().ok())
1923 {
1924 sleep(d).await;
1925 continue;
1926 }
1927
1928 dlg.finished(false);
1929
1930 return Err(match error {
1931 Ok(value) => common::Error::BadRequest(value),
1932 _ => common::Error::Failure(response),
1933 });
1934 }
1935 let response = {
1936 let bytes = common::to_bytes(body).await.unwrap_or_default();
1937 let encoded = common::to_string(&bytes);
1938 match serde_json::from_str(&encoded) {
1939 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1940 Err(error) => {
1941 dlg.response_json_decode_error(&encoded, &error);
1942 return Err(common::Error::JsonDecodeError(
1943 encoded.to_string(),
1944 error,
1945 ));
1946 }
1947 }
1948 };
1949
1950 dlg.finished(true);
1951 return Ok(response);
1952 }
1953 }
1954 }
1955 }
1956
1957 ///
1958 /// Sets the *request* property to the given value.
1959 ///
1960 /// Even though the property as already been set when instantiating this call,
1961 /// we provide this method for API completeness.
1962 pub fn request(mut self, new_value: RequestSyncDevicesRequest) -> DeviceRequestSyncCall<'a, C> {
1963 self._request = new_value;
1964 self
1965 }
1966 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1967 /// while executing the actual API request.
1968 ///
1969 /// ````text
1970 /// It should be used to handle progress information, and to implement a certain level of resilience.
1971 /// ````
1972 ///
1973 /// Sets the *delegate* property to the given value.
1974 pub fn delegate(
1975 mut self,
1976 new_value: &'a mut dyn common::Delegate,
1977 ) -> DeviceRequestSyncCall<'a, C> {
1978 self._delegate = Some(new_value);
1979 self
1980 }
1981
1982 /// Set any additional parameter of the query string used in the request.
1983 /// It should be used to set parameters which are not yet available through their own
1984 /// setters.
1985 ///
1986 /// Please note that this method must not be used to set any of the known parameters
1987 /// which have their own setter method. If done anyway, the request will fail.
1988 ///
1989 /// # Additional Parameters
1990 ///
1991 /// * *$.xgafv* (query-string) - V1 error format.
1992 /// * *access_token* (query-string) - OAuth access token.
1993 /// * *alt* (query-string) - Data format for response.
1994 /// * *callback* (query-string) - JSONP
1995 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1996 /// * *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.
1997 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1998 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1999 /// * *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.
2000 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2001 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2002 pub fn param<T>(mut self, name: T, value: T) -> DeviceRequestSyncCall<'a, C>
2003 where
2004 T: AsRef<str>,
2005 {
2006 self._additional_params
2007 .insert(name.as_ref().to_string(), value.as_ref().to_string());
2008 self
2009 }
2010
2011 /// Identifies the authorization scope for the method you are building.
2012 ///
2013 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2014 /// [`Scope::Full`].
2015 ///
2016 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2017 /// tokens for more than one scope.
2018 ///
2019 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2020 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2021 /// sufficient, a read-write scope will do as well.
2022 pub fn add_scope<St>(mut self, scope: St) -> DeviceRequestSyncCall<'a, C>
2023 where
2024 St: AsRef<str>,
2025 {
2026 self._scopes.insert(String::from(scope.as_ref()));
2027 self
2028 }
2029 /// Identifies the authorization scope(s) for the method you are building.
2030 ///
2031 /// See [`Self::add_scope()`] for details.
2032 pub fn add_scopes<I, St>(mut self, scopes: I) -> DeviceRequestSyncCall<'a, C>
2033 where
2034 I: IntoIterator<Item = St>,
2035 St: AsRef<str>,
2036 {
2037 self._scopes
2038 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2039 self
2040 }
2041
2042 /// Removes all scopes, and no default scope will be used either.
2043 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2044 /// for details).
2045 pub fn clear_scopes(mut self) -> DeviceRequestSyncCall<'a, C> {
2046 self._scopes.clear();
2047 self
2048 }
2049}
2050
2051/// Gets all the devices associated with the given third-party user. The third-party user's identity is passed in via the `agent_user_id` (see SyncRequest). This request must be authorized using service account credentials from your Actions console project.
2052///
2053/// A builder for the *sync* method supported by a *device* resource.
2054/// It is not used directly, but through a [`DeviceMethods`] instance.
2055///
2056/// # Example
2057///
2058/// Instantiate a resource method builder
2059///
2060/// ```test_harness,no_run
2061/// # extern crate hyper;
2062/// # extern crate hyper_rustls;
2063/// # extern crate google_homegraph1 as homegraph1;
2064/// use homegraph1::api::SyncRequest;
2065/// # async fn dox() {
2066/// # use homegraph1::{HomeGraphService, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2067///
2068/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2069/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
2070/// # .with_native_roots()
2071/// # .unwrap()
2072/// # .https_only()
2073/// # .enable_http2()
2074/// # .build();
2075///
2076/// # let executor = hyper_util::rt::TokioExecutor::new();
2077/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
2078/// # secret,
2079/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2080/// # yup_oauth2::client::CustomHyperClientBuilder::from(
2081/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
2082/// # ),
2083/// # ).build().await.unwrap();
2084///
2085/// # let client = hyper_util::client::legacy::Client::builder(
2086/// # hyper_util::rt::TokioExecutor::new()
2087/// # )
2088/// # .build(
2089/// # hyper_rustls::HttpsConnectorBuilder::new()
2090/// # .with_native_roots()
2091/// # .unwrap()
2092/// # .https_or_http()
2093/// # .enable_http2()
2094/// # .build()
2095/// # );
2096/// # let mut hub = HomeGraphService::new(client, auth);
2097/// // As the method needs a request, you would usually fill it with the desired information
2098/// // into the respective structure. Some of the parts shown here might not be applicable !
2099/// // Values shown here are possibly random and not representative !
2100/// let mut req = SyncRequest::default();
2101///
2102/// // You can configure optional parameters by calling the respective setters at will, and
2103/// // execute the final call using `doit()`.
2104/// // Values shown here are possibly random and not representative !
2105/// let result = hub.devices().sync(req)
2106/// .doit().await;
2107/// # }
2108/// ```
2109pub struct DeviceSyncCall<'a, C>
2110where
2111 C: 'a,
2112{
2113 hub: &'a HomeGraphService<C>,
2114 _request: SyncRequest,
2115 _delegate: Option<&'a mut dyn common::Delegate>,
2116 _additional_params: HashMap<String, String>,
2117 _scopes: BTreeSet<String>,
2118}
2119
2120impl<'a, C> common::CallBuilder for DeviceSyncCall<'a, C> {}
2121
2122impl<'a, C> DeviceSyncCall<'a, C>
2123where
2124 C: common::Connector,
2125{
2126 /// Perform the operation you have build so far.
2127 pub async fn doit(mut self) -> common::Result<(common::Response, SyncResponse)> {
2128 use std::borrow::Cow;
2129 use std::io::{Read, Seek};
2130
2131 use common::{url::Params, ToParts};
2132 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2133
2134 let mut dd = common::DefaultDelegate;
2135 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2136 dlg.begin(common::MethodInfo {
2137 id: "homegraph.devices.sync",
2138 http_method: hyper::Method::POST,
2139 });
2140
2141 for &field in ["alt"].iter() {
2142 if self._additional_params.contains_key(field) {
2143 dlg.finished(false);
2144 return Err(common::Error::FieldClash(field));
2145 }
2146 }
2147
2148 let mut params = Params::with_capacity(3 + self._additional_params.len());
2149
2150 params.extend(self._additional_params.iter());
2151
2152 params.push("alt", "json");
2153 let mut url = self.hub._base_url.clone() + "v1/devices:sync";
2154 if self._scopes.is_empty() {
2155 self._scopes.insert(Scope::Full.as_ref().to_string());
2156 }
2157
2158 let url = params.parse_with_url(&url);
2159
2160 let mut json_mime_type = mime::APPLICATION_JSON;
2161 let mut request_value_reader = {
2162 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2163 common::remove_json_null_values(&mut value);
2164 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2165 serde_json::to_writer(&mut dst, &value).unwrap();
2166 dst
2167 };
2168 let request_size = request_value_reader
2169 .seek(std::io::SeekFrom::End(0))
2170 .unwrap();
2171 request_value_reader
2172 .seek(std::io::SeekFrom::Start(0))
2173 .unwrap();
2174
2175 loop {
2176 let token = match self
2177 .hub
2178 .auth
2179 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2180 .await
2181 {
2182 Ok(token) => token,
2183 Err(e) => match dlg.token(e) {
2184 Ok(token) => token,
2185 Err(e) => {
2186 dlg.finished(false);
2187 return Err(common::Error::MissingToken(e));
2188 }
2189 },
2190 };
2191 request_value_reader
2192 .seek(std::io::SeekFrom::Start(0))
2193 .unwrap();
2194 let mut req_result = {
2195 let client = &self.hub.client;
2196 dlg.pre_request();
2197 let mut req_builder = hyper::Request::builder()
2198 .method(hyper::Method::POST)
2199 .uri(url.as_str())
2200 .header(USER_AGENT, self.hub._user_agent.clone());
2201
2202 if let Some(token) = token.as_ref() {
2203 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2204 }
2205
2206 let request = req_builder
2207 .header(CONTENT_TYPE, json_mime_type.to_string())
2208 .header(CONTENT_LENGTH, request_size as u64)
2209 .body(common::to_body(
2210 request_value_reader.get_ref().clone().into(),
2211 ));
2212
2213 client.request(request.unwrap()).await
2214 };
2215
2216 match req_result {
2217 Err(err) => {
2218 if let common::Retry::After(d) = dlg.http_error(&err) {
2219 sleep(d).await;
2220 continue;
2221 }
2222 dlg.finished(false);
2223 return Err(common::Error::HttpError(err));
2224 }
2225 Ok(res) => {
2226 let (mut parts, body) = res.into_parts();
2227 let mut body = common::Body::new(body);
2228 if !parts.status.is_success() {
2229 let bytes = common::to_bytes(body).await.unwrap_or_default();
2230 let error = serde_json::from_str(&common::to_string(&bytes));
2231 let response = common::to_response(parts, bytes.into());
2232
2233 if let common::Retry::After(d) =
2234 dlg.http_failure(&response, error.as_ref().ok())
2235 {
2236 sleep(d).await;
2237 continue;
2238 }
2239
2240 dlg.finished(false);
2241
2242 return Err(match error {
2243 Ok(value) => common::Error::BadRequest(value),
2244 _ => common::Error::Failure(response),
2245 });
2246 }
2247 let response = {
2248 let bytes = common::to_bytes(body).await.unwrap_or_default();
2249 let encoded = common::to_string(&bytes);
2250 match serde_json::from_str(&encoded) {
2251 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2252 Err(error) => {
2253 dlg.response_json_decode_error(&encoded, &error);
2254 return Err(common::Error::JsonDecodeError(
2255 encoded.to_string(),
2256 error,
2257 ));
2258 }
2259 }
2260 };
2261
2262 dlg.finished(true);
2263 return Ok(response);
2264 }
2265 }
2266 }
2267 }
2268
2269 ///
2270 /// Sets the *request* property to the given value.
2271 ///
2272 /// Even though the property as already been set when instantiating this call,
2273 /// we provide this method for API completeness.
2274 pub fn request(mut self, new_value: SyncRequest) -> DeviceSyncCall<'a, C> {
2275 self._request = new_value;
2276 self
2277 }
2278 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2279 /// while executing the actual API request.
2280 ///
2281 /// ````text
2282 /// It should be used to handle progress information, and to implement a certain level of resilience.
2283 /// ````
2284 ///
2285 /// Sets the *delegate* property to the given value.
2286 pub fn delegate(mut self, new_value: &'a mut dyn common::Delegate) -> DeviceSyncCall<'a, C> {
2287 self._delegate = Some(new_value);
2288 self
2289 }
2290
2291 /// Set any additional parameter of the query string used in the request.
2292 /// It should be used to set parameters which are not yet available through their own
2293 /// setters.
2294 ///
2295 /// Please note that this method must not be used to set any of the known parameters
2296 /// which have their own setter method. If done anyway, the request will fail.
2297 ///
2298 /// # Additional Parameters
2299 ///
2300 /// * *$.xgafv* (query-string) - V1 error format.
2301 /// * *access_token* (query-string) - OAuth access token.
2302 /// * *alt* (query-string) - Data format for response.
2303 /// * *callback* (query-string) - JSONP
2304 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2305 /// * *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.
2306 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2307 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2308 /// * *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.
2309 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2310 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2311 pub fn param<T>(mut self, name: T, value: T) -> DeviceSyncCall<'a, C>
2312 where
2313 T: AsRef<str>,
2314 {
2315 self._additional_params
2316 .insert(name.as_ref().to_string(), value.as_ref().to_string());
2317 self
2318 }
2319
2320 /// Identifies the authorization scope for the method you are building.
2321 ///
2322 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2323 /// [`Scope::Full`].
2324 ///
2325 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2326 /// tokens for more than one scope.
2327 ///
2328 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2329 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2330 /// sufficient, a read-write scope will do as well.
2331 pub fn add_scope<St>(mut self, scope: St) -> DeviceSyncCall<'a, C>
2332 where
2333 St: AsRef<str>,
2334 {
2335 self._scopes.insert(String::from(scope.as_ref()));
2336 self
2337 }
2338 /// Identifies the authorization scope(s) for the method you are building.
2339 ///
2340 /// See [`Self::add_scope()`] for details.
2341 pub fn add_scopes<I, St>(mut self, scopes: I) -> DeviceSyncCall<'a, C>
2342 where
2343 I: IntoIterator<Item = St>,
2344 St: AsRef<str>,
2345 {
2346 self._scopes
2347 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2348 self
2349 }
2350
2351 /// Removes all scopes, and no default scope will be used either.
2352 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2353 /// for details).
2354 pub fn clear_scopes(mut self) -> DeviceSyncCall<'a, C> {
2355 self._scopes.clear();
2356 self
2357 }
2358}