google_analyticsreporting4/api.rs
1#![allow(clippy::ptr_arg)]
2
3use std::collections::{BTreeSet, HashMap};
4
5use tokio::time::sleep;
6
7// ##############
8// UTILITIES ###
9// ############
10
11/// Identifies the an OAuth2 authorization scope.
12/// A scope is needed when requesting an
13/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
14#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
15pub enum Scope {
16 /// View and manage your Google Analytics data
17 Analytic,
18
19 /// See and download your Google Analytics data
20 AnalyticReadonly,
21}
22
23impl AsRef<str> for Scope {
24 fn as_ref(&self) -> &str {
25 match *self {
26 Scope::Analytic => "https://www.googleapis.com/auth/analytics",
27 Scope::AnalyticReadonly => "https://www.googleapis.com/auth/analytics.readonly",
28 }
29 }
30}
31
32#[allow(clippy::derivable_impls)]
33impl Default for Scope {
34 fn default() -> Scope {
35 Scope::AnalyticReadonly
36 }
37}
38
39// ########
40// HUB ###
41// ######
42
43/// Central instance to access all AnalyticsReporting related resource activities
44///
45/// # Examples
46///
47/// Instantiate a new hub
48///
49/// ```test_harness,no_run
50/// extern crate hyper;
51/// extern crate hyper_rustls;
52/// extern crate google_analyticsreporting4 as analyticsreporting4;
53/// use analyticsreporting4::api::SearchUserActivityRequest;
54/// use analyticsreporting4::{Result, Error};
55/// # async fn dox() {
56/// use analyticsreporting4::{AnalyticsReporting, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
57///
58/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
59/// // `client_secret`, among other things.
60/// let secret: yup_oauth2::ApplicationSecret = Default::default();
61/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
62/// // unless you replace `None` with the desired Flow.
63/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
64/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
65/// // retrieve them from storage.
66/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
67/// secret,
68/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
69/// ).build().await.unwrap();
70///
71/// let client = hyper_util::client::legacy::Client::builder(
72/// hyper_util::rt::TokioExecutor::new()
73/// )
74/// .build(
75/// hyper_rustls::HttpsConnectorBuilder::new()
76/// .with_native_roots()
77/// .unwrap()
78/// .https_or_http()
79/// .enable_http1()
80/// .build()
81/// );
82/// let mut hub = AnalyticsReporting::new(client, auth);
83/// // As the method needs a request, you would usually fill it with the desired information
84/// // into the respective structure. Some of the parts shown here might not be applicable !
85/// // Values shown here are possibly random and not representative !
86/// let mut req = SearchUserActivityRequest::default();
87///
88/// // You can configure optional parameters by calling the respective setters at will, and
89/// // execute the final call using `doit()`.
90/// // Values shown here are possibly random and not representative !
91/// let result = hub.user_activity().search(req)
92/// .doit().await;
93///
94/// match result {
95/// Err(e) => match e {
96/// // The Error enum provides details about what exactly happened.
97/// // You can also just use its `Debug`, `Display` or `Error` traits
98/// Error::HttpError(_)
99/// |Error::Io(_)
100/// |Error::MissingAPIKey
101/// |Error::MissingToken(_)
102/// |Error::Cancelled
103/// |Error::UploadSizeLimitExceeded(_, _)
104/// |Error::Failure(_)
105/// |Error::BadRequest(_)
106/// |Error::FieldClash(_)
107/// |Error::JsonDecodeError(_, _) => println!("{}", e),
108/// },
109/// Ok(res) => println!("Success: {:?}", res),
110/// }
111/// # }
112/// ```
113#[derive(Clone)]
114pub struct AnalyticsReporting<C> {
115 pub client: common::Client<C>,
116 pub auth: Box<dyn common::GetToken>,
117 _user_agent: String,
118 _base_url: String,
119 _root_url: String,
120}
121
122impl<C> common::Hub for AnalyticsReporting<C> {}
123
124impl<'a, C> AnalyticsReporting<C> {
125 pub fn new<A: 'static + common::GetToken>(
126 client: common::Client<C>,
127 auth: A,
128 ) -> AnalyticsReporting<C> {
129 AnalyticsReporting {
130 client,
131 auth: Box::new(auth),
132 _user_agent: "google-api-rust-client/6.0.0".to_string(),
133 _base_url: "https://analyticsreporting.googleapis.com/".to_string(),
134 _root_url: "https://analyticsreporting.googleapis.com/".to_string(),
135 }
136 }
137
138 pub fn reports(&'a self) -> ReportMethods<'a, C> {
139 ReportMethods { hub: self }
140 }
141 pub fn user_activity(&'a self) -> UserActivityMethods<'a, C> {
142 UserActivityMethods { hub: self }
143 }
144
145 /// Set the user-agent header field to use in all requests to the server.
146 /// It defaults to `google-api-rust-client/6.0.0`.
147 ///
148 /// Returns the previously set user-agent.
149 pub fn user_agent(&mut self, agent_name: String) -> String {
150 std::mem::replace(&mut self._user_agent, agent_name)
151 }
152
153 /// Set the base url to use in all requests to the server.
154 /// It defaults to `https://analyticsreporting.googleapis.com/`.
155 ///
156 /// Returns the previously set base url.
157 pub fn base_url(&mut self, new_base_url: String) -> String {
158 std::mem::replace(&mut self._base_url, new_base_url)
159 }
160
161 /// Set the root url to use in all requests to the server.
162 /// It defaults to `https://analyticsreporting.googleapis.com/`.
163 ///
164 /// Returns the previously set root url.
165 pub fn root_url(&mut self, new_root_url: String) -> String {
166 std::mem::replace(&mut self._root_url, new_root_url)
167 }
168}
169
170// ############
171// SCHEMAS ###
172// ##########
173/// An Activity represents data for an activity of a user. Note that an Activity is different from a hit. A hit might result in multiple Activity's. For example, if a hit includes a transaction and a goal completion, there will be two Activity protos for this hit, one for ECOMMERCE and one for GOAL. Conversely, multiple hits can also construct one Activity. In classic e-commerce, data for one transaction might be sent through multiple hits. These hits will be merged into one ECOMMERCE Activity.
174///
175/// This type is not used in any activity, and only used as *part* of another schema.
176///
177#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
178#[serde_with::serde_as]
179#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
180pub struct Activity {
181 /// Timestamp of the activity. If activities for a visit cross midnight and occur in two separate dates, then two sessions (one per date) share the session identifier. For example, say session ID 113472 has activity within 2019-08-20, and session ID 243742 has activity within 2019-08-25 and 2019-08-26. Session ID 113472 is one session, and session ID 243742 is two sessions.
182 #[serde(rename = "activityTime")]
183 pub activity_time: Option<chrono::DateTime<chrono::offset::Utc>>,
184 /// Type of this activity.
185 #[serde(rename = "activityType")]
186 pub activity_type: Option<String>,
187 /// This will be set if `activity_type` equals `SCREEN_VIEW`.
188 pub appview: Option<ScreenviewData>,
189 /// For manual campaign tracking, it is the value of the utm_campaign campaign tracking parameter. For AdWords autotagging, it is the name(s) of the online ad campaign(s) you use for the property. If you use neither, its value is (not set).
190 pub campaign: Option<String>,
191 /// The Channel Group associated with an end user's session for this View (defined by the View's Channel Groupings).
192 #[serde(rename = "channelGrouping")]
193 pub channel_grouping: Option<String>,
194 /// A list of all custom dimensions associated with this activity.
195 #[serde(rename = "customDimension")]
196 pub custom_dimension: Option<Vec<CustomDimension>>,
197 /// This will be set if `activity_type` equals `ECOMMERCE`.
198 pub ecommerce: Option<EcommerceData>,
199 /// This field contains all the details pertaining to an event and will be set if `activity_type` equals `EVENT`.
200 pub event: Option<EventData>,
201 /// This field contains a list of all the goals that were reached in this activity when `activity_type` equals `GOAL`.
202 pub goals: Option<GoalSetData>,
203 /// The hostname from which the tracking request was made.
204 pub hostname: Option<String>,
205 /// For manual campaign tracking, it is the value of the utm_term campaign tracking parameter. For AdWords traffic, it contains the best matching targeting criteria. For the display network, where multiple targeting criteria could have caused the ad to show up, it returns the best matching targeting criteria as selected by Ads. This could be display_keyword, site placement, boomuserlist, user_interest, age, or gender. Otherwise its value is (not set).
206 pub keyword: Option<String>,
207 /// The first page in users' sessions, or the landing page.
208 #[serde(rename = "landingPagePath")]
209 pub landing_page_path: Option<String>,
210 /// The type of referrals. For manual campaign tracking, it is the value of the utm_medium campaign tracking parameter. For AdWords autotagging, it is cpc. If users came from a search engine detected by Google Analytics, it is organic. If the referrer is not a search engine, it is referral. If users came directly to the property and document.referrer is empty, its value is (none).
211 pub medium: Option<String>,
212 /// This will be set if `activity_type` equals `PAGEVIEW`. This field contains all the details about the visitor and the page that was visited.
213 pub pageview: Option<PageviewData>,
214 /// The source of referrals. For manual campaign tracking, it is the value of the utm_source campaign tracking parameter. For AdWords autotagging, it is google. If you use neither, it is the domain of the source (e.g., document.referrer) referring the users. It may also contain a port address. If users arrived without a referrer, its value is (direct).
215 pub source: Option<String>,
216}
217
218impl common::Part for Activity {}
219
220/// Defines a cohort. A cohort is a group of users who share a common characteristic. For example, all users with the same acquisition date belong to the same cohort.
221///
222/// This type is not used in any activity, and only used as *part* of another schema.
223///
224#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
225#[serde_with::serde_as]
226#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
227pub struct Cohort {
228 /// This is used for `FIRST_VISIT_DATE` cohort, the cohort selects users whose first visit date is between start date and end date defined in the DateRange. The date ranges should be aligned for cohort requests. If the request contains `ga:cohortNthDay` it should be exactly one day long, if `ga:cohortNthWeek` it should be aligned to the week boundary (starting at Sunday and ending Saturday), and for `ga:cohortNthMonth` the date range should be aligned to the month (starting at the first and ending on the last day of the month). For LTV requests there are no such restrictions. You do not need to supply a date range for the `reportsRequest.dateRanges` field.
229 #[serde(rename = "dateRange")]
230 pub date_range: Option<DateRange>,
231 /// A unique name for the cohort. If not defined name will be auto-generated with values cohort_[1234...].
232 pub name: Option<String>,
233 /// Type of the cohort. The only supported type as of now is `FIRST_VISIT_DATE`. If this field is unspecified the cohort is treated as `FIRST_VISIT_DATE` type cohort.
234 #[serde(rename = "type")]
235 pub type_: Option<String>,
236}
237
238impl common::Part for Cohort {}
239
240/// Defines a cohort group. For example: "cohortGroup": { "cohorts": [{ "name": "cohort 1", "type": "FIRST_VISIT_DATE", "dateRange": { "startDate": "2015-08-01", "endDate": "2015-08-01" } },{ "name": "cohort 2" "type": "FIRST_VISIT_DATE" "dateRange": { "startDate": "2015-07-01", "endDate": "2015-07-01" } }] }
241///
242/// This type is not used in any activity, and only used as *part* of another schema.
243///
244#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
245#[serde_with::serde_as]
246#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
247pub struct CohortGroup {
248 /// The definition for the cohort.
249 pub cohorts: Option<Vec<Cohort>>,
250 /// Enable Life Time Value (LTV). LTV measures lifetime value for users acquired through different channels. Please see: [Cohort Analysis](https://support.google.com/analytics/answer/6074676) and [Lifetime Value](https://support.google.com/analytics/answer/6182550) If the value of lifetimeValue is false: - The metric values are similar to the values in the web interface cohort report. - The cohort definition date ranges must be aligned to the calendar week and month. i.e. while requesting `ga:cohortNthWeek` the `startDate` in the cohort definition should be a Sunday and the `endDate` should be the following Saturday, and for `ga:cohortNthMonth`, the `startDate` should be the 1st of the month and `endDate` should be the last day of the month. When the lifetimeValue is true: - The metric values will correspond to the values in the web interface LifeTime value report. - The Lifetime Value report shows you how user value (Revenue) and engagement (Appviews, Goal Completions, Sessions, and Session Duration) grow during the 90 days after a user is acquired. - The metrics are calculated as a cumulative average per user per the time increment. - The cohort definition date ranges need not be aligned to the calendar week and month boundaries. - The `viewId` must be an [app view ID](https://support.google.com/analytics/answer/2649553#WebVersusAppViews)
251 #[serde(rename = "lifetimeValue")]
252 pub lifetime_value: Option<bool>,
253}
254
255impl common::Part for CohortGroup {}
256
257/// Column headers.
258///
259/// This type is not used in any activity, and only used as *part* of another schema.
260///
261#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
262#[serde_with::serde_as]
263#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
264pub struct ColumnHeader {
265 /// The dimension names in the response.
266 pub dimensions: Option<Vec<String>>,
267 /// Metric headers for the metrics in the response.
268 #[serde(rename = "metricHeader")]
269 pub metric_header: Option<MetricHeader>,
270}
271
272impl common::Part for ColumnHeader {}
273
274/// Custom dimension.
275///
276/// This type is not used in any activity, and only used as *part* of another schema.
277///
278#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
279#[serde_with::serde_as]
280#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
281pub struct CustomDimension {
282 /// Slot number of custom dimension.
283 pub index: Option<i32>,
284 /// Value of the custom dimension. Default value (i.e. empty string) indicates clearing sesion/visitor scope custom dimension value.
285 pub value: Option<String>,
286}
287
288impl common::Part for CustomDimension {}
289
290/// A contiguous set of days: startDate, startDate + 1 day, ..., endDate. The start and end dates are specified in [ISO8601](https://en.wikipedia.org/wiki/ISO_8601) date format `YYYY-MM-DD`.
291///
292/// This type is not used in any activity, and only used as *part* of another schema.
293///
294#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
295#[serde_with::serde_as]
296#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
297pub struct DateRange {
298 /// The end date for the query in the format `YYYY-MM-DD`.
299 #[serde(rename = "endDate")]
300 pub end_date: Option<String>,
301 /// The start date for the query in the format `YYYY-MM-DD`.
302 #[serde(rename = "startDate")]
303 pub start_date: Option<String>,
304}
305
306impl common::Part for DateRange {}
307
308/// Used to return a list of metrics for a single DateRange / dimension combination
309///
310/// This type is not used in any activity, and only used as *part* of another schema.
311///
312#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
313#[serde_with::serde_as]
314#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
315pub struct DateRangeValues {
316 /// The values of each pivot region.
317 #[serde(rename = "pivotValueRegions")]
318 pub pivot_value_regions: Option<Vec<PivotValueRegion>>,
319 /// Each value corresponds to each Metric in the request.
320 pub values: Option<Vec<String>>,
321}
322
323impl common::Part for DateRangeValues {}
324
325/// [Dimensions](https://support.google.com/analytics/answer/1033861) are attributes of your data. For example, the dimension `ga:city` indicates the city, for example, "Paris" or "New York", from which a session originates.
326///
327/// This type is not used in any activity, and only used as *part* of another schema.
328///
329#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
330#[serde_with::serde_as]
331#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
332pub struct Dimension {
333 /// If non-empty, we place dimension values into buckets after string to int64. Dimension values that are not the string representation of an integral value will be converted to zero. The bucket values have to be in increasing order. Each bucket is closed on the lower end, and open on the upper end. The "first" bucket includes all values less than the first boundary, the "last" bucket includes all values up to infinity. Dimension values that fall in a bucket get transformed to a new dimension value. For example, if one gives a list of "0, 1, 3, 4, 7", then we return the following buckets: - bucket #1: values < 0, dimension value "<0" - bucket #2: values in [0,1), dimension value "0" - bucket #3: values in [1,3), dimension value "1-2" - bucket #4: values in [3,4), dimension value "3" - bucket #5: values in [4,7), dimension value "4-6" - bucket #6: values >= 7, dimension value "7+" NOTE: If you are applying histogram mutation on any dimension, and using that dimension in sort, you will want to use the sort type `HISTOGRAM_BUCKET` for that purpose. Without that the dimension values will be sorted according to dictionary (lexicographic) order. For example the ascending dictionary order is: "<50", "1001+", "121-1000", "50-120" And the ascending `HISTOGRAM_BUCKET` order is: "<50", "50-120", "121-1000", "1001+" The client has to explicitly request `"orderType": "HISTOGRAM_BUCKET"` for a histogram-mutated dimension.
334 #[serde(rename = "histogramBuckets")]
335 #[serde_as(as = "Option<Vec<serde_with::DisplayFromStr>>")]
336 pub histogram_buckets: Option<Vec<i64>>,
337 /// Name of the dimension to fetch, for example `ga:browser`.
338 pub name: Option<String>,
339}
340
341impl common::Part for Dimension {}
342
343/// Dimension filter specifies the filtering options on a dimension.
344///
345/// This type is not used in any activity, and only used as *part* of another schema.
346///
347#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
348#[serde_with::serde_as]
349#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
350pub struct DimensionFilter {
351 /// Should the match be case sensitive? Default is false.
352 #[serde(rename = "caseSensitive")]
353 pub case_sensitive: Option<bool>,
354 /// The dimension to filter on. A DimensionFilter must contain a dimension.
355 #[serde(rename = "dimensionName")]
356 pub dimension_name: Option<String>,
357 /// Strings or regular expression to match against. Only the first value of the list is used for comparison unless the operator is `IN_LIST`. If `IN_LIST` operator, then the entire list is used to filter the dimensions as explained in the description of the `IN_LIST` operator.
358 pub expressions: Option<Vec<String>>,
359 /// Logical `NOT` operator. If this boolean is set to true, then the matching dimension values will be excluded in the report. The default is false.
360 pub not: Option<bool>,
361 /// How to match the dimension to the expression. The default is REGEXP.
362 pub operator: Option<String>,
363}
364
365impl common::Part for DimensionFilter {}
366
367/// A group of dimension filters. Set the operator value to specify how the filters are logically combined.
368///
369/// This type is not used in any activity, and only used as *part* of another schema.
370///
371#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
372#[serde_with::serde_as]
373#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
374pub struct DimensionFilterClause {
375 /// The repeated set of filters. They are logically combined based on the operator specified.
376 pub filters: Option<Vec<DimensionFilter>>,
377 /// The operator for combining multiple dimension filters. If unspecified, it is treated as an `OR`.
378 pub operator: Option<String>,
379}
380
381impl common::Part for DimensionFilterClause {}
382
383/// Dynamic segment definition for defining the segment within the request. A segment can select users, sessions or both.
384///
385/// This type is not used in any activity, and only used as *part* of another schema.
386///
387#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
388#[serde_with::serde_as]
389#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
390pub struct DynamicSegment {
391 /// The name of the dynamic segment.
392 pub name: Option<String>,
393 /// Session Segment to select sessions to include in the segment.
394 #[serde(rename = "sessionSegment")]
395 pub session_segment: Option<SegmentDefinition>,
396 /// User Segment to select users to include in the segment.
397 #[serde(rename = "userSegment")]
398 pub user_segment: Option<SegmentDefinition>,
399}
400
401impl common::Part for DynamicSegment {}
402
403/// E-commerce details associated with the user activity.
404///
405/// This type is not used in any activity, and only used as *part* of another schema.
406///
407#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
408#[serde_with::serde_as]
409#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
410pub struct EcommerceData {
411 /// Action associated with this e-commerce action.
412 #[serde(rename = "actionType")]
413 pub action_type: Option<String>,
414 /// The type of this e-commerce activity.
415 #[serde(rename = "ecommerceType")]
416 pub ecommerce_type: Option<String>,
417 /// Details of the products in this transaction.
418 pub products: Option<Vec<ProductData>>,
419 /// Transaction details of this e-commerce action.
420 pub transaction: Option<TransactionData>,
421}
422
423impl common::Part for EcommerceData {}
424
425/// Represents all the details pertaining to an event.
426///
427/// This type is not used in any activity, and only used as *part* of another schema.
428///
429#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
430#[serde_with::serde_as]
431#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
432pub struct EventData {
433 /// Type of interaction with the object. Eg: 'play'.
434 #[serde(rename = "eventAction")]
435 pub event_action: Option<String>,
436 /// The object on the page that was interacted with. Eg: 'Video'.
437 #[serde(rename = "eventCategory")]
438 pub event_category: Option<String>,
439 /// Number of such events in this activity.
440 #[serde(rename = "eventCount")]
441 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
442 pub event_count: Option<i64>,
443 /// Label attached with the event.
444 #[serde(rename = "eventLabel")]
445 pub event_label: Option<String>,
446 /// Numeric value associated with the event.
447 #[serde(rename = "eventValue")]
448 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
449 pub event_value: Option<i64>,
450}
451
452impl common::Part for EventData {}
453
454/// The batch request containing multiple report request.
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/// * [batch get reports](ReportBatchGetCall) (request)
462#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
463#[serde_with::serde_as]
464#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
465pub struct GetReportsRequest {
466 /// Requests, each request will have a separate response. There can be a maximum of 5 requests. All requests should have the same `dateRanges`, `viewId`, `segments`, `samplingLevel`, and `cohortGroup`.
467 #[serde(rename = "reportRequests")]
468 pub report_requests: Option<Vec<ReportRequest>>,
469 /// Enables [resource based quotas](https://developers.google.com/analytics/devguides/reporting/core/v4/limits-quotas#analytics_reporting_api_v4), (defaults to `False`). If this field is set to `True` the per view (profile) quotas are governed by the computational cost of the request. Note that using cost based quotas will higher enable sampling rates. (10 Million for `SMALL`, 100M for `LARGE`. See the [limits and quotas documentation](https://developers.google.com/analytics/devguides/reporting/core/v4/limits-quotas#analytics_reporting_api_v4) for details.
470 #[serde(rename = "useResourceQuotas")]
471 pub use_resource_quotas: Option<bool>,
472}
473
474impl common::RequestValue for GetReportsRequest {}
475
476/// The main response class which holds the reports from the Reporting API `batchGet` call.
477///
478/// # Activities
479///
480/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
481/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
482///
483/// * [batch get reports](ReportBatchGetCall) (response)
484#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
485#[serde_with::serde_as]
486#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
487pub struct GetReportsResponse {
488 /// The amount of resource quota tokens deducted to execute the query. Includes all responses.
489 #[serde(rename = "queryCost")]
490 pub query_cost: Option<i32>,
491 /// Responses corresponding to each of the request.
492 pub reports: Option<Vec<Report>>,
493 /// The amount of resource quota remaining for the property.
494 #[serde(rename = "resourceQuotasRemaining")]
495 pub resource_quotas_remaining: Option<ResourceQuotasRemaining>,
496}
497
498impl common::ResponseResult for GetReportsResponse {}
499
500/// Represents all the details pertaining to a goal.
501///
502/// This type is not used in any activity, and only used as *part* of another schema.
503///
504#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
505#[serde_with::serde_as]
506#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
507pub struct GoalData {
508 /// URL of the page where this goal was completed.
509 #[serde(rename = "goalCompletionLocation")]
510 pub goal_completion_location: Option<String>,
511 /// Total number of goal completions in this activity.
512 #[serde(rename = "goalCompletions")]
513 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
514 pub goal_completions: Option<i64>,
515 /// This identifies the goal as configured for the profile.
516 #[serde(rename = "goalIndex")]
517 pub goal_index: Option<i32>,
518 /// Name of the goal.
519 #[serde(rename = "goalName")]
520 pub goal_name: Option<String>,
521 /// URL of the page one step prior to the goal completion.
522 #[serde(rename = "goalPreviousStep1")]
523 pub goal_previous_step1: Option<String>,
524 /// URL of the page two steps prior to the goal completion.
525 #[serde(rename = "goalPreviousStep2")]
526 pub goal_previous_step2: Option<String>,
527 /// URL of the page three steps prior to the goal completion.
528 #[serde(rename = "goalPreviousStep3")]
529 pub goal_previous_step3: Option<String>,
530 /// Value in this goal.
531 #[serde(rename = "goalValue")]
532 pub goal_value: Option<f64>,
533}
534
535impl common::Part for GoalData {}
536
537/// Represents a set of goals that were reached in an activity.
538///
539/// This type is not used in any activity, and only used as *part* of another schema.
540///
541#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
542#[serde_with::serde_as]
543#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
544pub struct GoalSetData {
545 /// All the goals that were reached in the current activity.
546 pub goals: Option<Vec<GoalData>>,
547}
548
549impl common::Part for GoalSetData {}
550
551/// [Metrics](https://support.google.com/analytics/answer/1033861) are the quantitative measurements. For example, the metric `ga:users` indicates the total number of users for the requested time period.
552///
553/// This type is not used in any activity, and only used as *part* of another schema.
554///
555#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
556#[serde_with::serde_as]
557#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
558pub struct Metric {
559 /// An alias for the metric expression is an alternate name for the expression. The alias can be used for filtering and sorting. This field is optional and is useful if the expression is not a single metric but a complex expression which cannot be used in filtering and sorting. The alias is also used in the response column header.
560 pub alias: Option<String>,
561 /// A metric expression in the request. An expression is constructed from one or more metrics and numbers. Accepted operators include: Plus (+), Minus (-), Negation (Unary -), Divided by (/), Multiplied by (*), Parenthesis, Positive cardinal numbers (0-9), can include decimals and is limited to 1024 characters. Example `ga:totalRefunds/ga:users`, in most cases the metric expression is just a single metric name like `ga:users`. Adding mixed `MetricType` (E.g., `CURRENCY` + `PERCENTAGE`) metrics will result in unexpected results.
562 pub expression: Option<String>,
563 /// Specifies how the metric expression should be formatted, for example `INTEGER`.
564 #[serde(rename = "formattingType")]
565 pub formatting_type: Option<String>,
566}
567
568impl common::Part for Metric {}
569
570/// MetricFilter specifies the filter on a metric.
571///
572/// This type is not used in any activity, and only used as *part* of another schema.
573///
574#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
575#[serde_with::serde_as]
576#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
577pub struct MetricFilter {
578 /// The value to compare against.
579 #[serde(rename = "comparisonValue")]
580 pub comparison_value: Option<String>,
581 /// The metric that will be filtered on. A metricFilter must contain a metric name. A metric name can be an alias earlier defined as a metric or it can also be a metric expression.
582 #[serde(rename = "metricName")]
583 pub metric_name: Option<String>,
584 /// Logical `NOT` operator. If this boolean is set to true, then the matching metric values will be excluded in the report. The default is false.
585 pub not: Option<bool>,
586 /// Is the metric `EQUAL`, `LESS_THAN` or `GREATER_THAN` the comparisonValue, the default is `EQUAL`. If the operator is `IS_MISSING`, checks if the metric is missing and would ignore the comparisonValue.
587 pub operator: Option<String>,
588}
589
590impl common::Part for MetricFilter {}
591
592/// Represents a group of metric filters. Set the operator value to specify how the filters are logically combined.
593///
594/// This type is not used in any activity, and only used as *part* of another schema.
595///
596#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
597#[serde_with::serde_as]
598#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
599pub struct MetricFilterClause {
600 /// The repeated set of filters. They are logically combined based on the operator specified.
601 pub filters: Option<Vec<MetricFilter>>,
602 /// The operator for combining multiple metric filters. If unspecified, it is treated as an `OR`.
603 pub operator: Option<String>,
604}
605
606impl common::Part for MetricFilterClause {}
607
608/// The headers for the metrics.
609///
610/// This type is not used in any activity, and only used as *part* of another schema.
611///
612#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
613#[serde_with::serde_as]
614#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
615pub struct MetricHeader {
616 /// Headers for the metrics in the response.
617 #[serde(rename = "metricHeaderEntries")]
618 pub metric_header_entries: Option<Vec<MetricHeaderEntry>>,
619 /// Headers for the pivots in the response.
620 #[serde(rename = "pivotHeaders")]
621 pub pivot_headers: Option<Vec<PivotHeader>>,
622}
623
624impl common::Part for MetricHeader {}
625
626/// Header for the metrics.
627///
628/// This type is not used in any activity, and only used as *part* of another schema.
629///
630#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
631#[serde_with::serde_as]
632#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
633pub struct MetricHeaderEntry {
634 /// The name of the header.
635 pub name: Option<String>,
636 /// The type of the metric, for example `INTEGER`.
637 #[serde(rename = "type")]
638 pub type_: Option<String>,
639}
640
641impl common::Part for MetricHeaderEntry {}
642
643/// A list of segment filters in the `OR` group are combined with the logical OR operator.
644///
645/// This type is not used in any activity, and only used as *part* of another schema.
646///
647#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
648#[serde_with::serde_as]
649#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
650pub struct OrFiltersForSegment {
651 /// List of segment filters to be combined with a `OR` operator.
652 #[serde(rename = "segmentFilterClauses")]
653 pub segment_filter_clauses: Option<Vec<SegmentFilterClause>>,
654}
655
656impl common::Part for OrFiltersForSegment {}
657
658/// Specifies the sorting options.
659///
660/// This type is not used in any activity, and only used as *part* of another schema.
661///
662#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
663#[serde_with::serde_as]
664#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
665pub struct OrderBy {
666 /// The field which to sort by. The default sort order is ascending. Example: `ga:browser`. Note, that you can only specify one field for sort here. For example, `ga:browser, ga:city` is not valid.
667 #[serde(rename = "fieldName")]
668 pub field_name: Option<String>,
669 /// The order type. The default orderType is `VALUE`.
670 #[serde(rename = "orderType")]
671 pub order_type: Option<String>,
672 /// The sorting order for the field.
673 #[serde(rename = "sortOrder")]
674 pub sort_order: Option<String>,
675}
676
677impl common::Part for OrderBy {}
678
679/// Represents details collected when the visitor views a page.
680///
681/// This type is not used in any activity, and only used as *part* of another schema.
682///
683#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
684#[serde_with::serde_as]
685#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
686pub struct PageviewData {
687 /// The URL of the page that the visitor viewed.
688 #[serde(rename = "pagePath")]
689 pub page_path: Option<String>,
690 /// The title of the page that the visitor viewed.
691 #[serde(rename = "pageTitle")]
692 pub page_title: Option<String>,
693}
694
695impl common::Part for PageviewData {}
696
697/// The Pivot describes the pivot section in the request. The Pivot helps rearrange the information in the table for certain reports by pivoting your data on a second dimension.
698///
699/// This type is not used in any activity, and only used as *part* of another schema.
700///
701#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
702#[serde_with::serde_as]
703#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
704pub struct Pivot {
705 /// DimensionFilterClauses are logically combined with an `AND` operator: only data that is included by all these DimensionFilterClauses contributes to the values in this pivot region. Dimension filters can be used to restrict the columns shown in the pivot region. For example if you have `ga:browser` as the requested dimension in the pivot region, and you specify key filters to restrict `ga:browser` to only "IE" or "Firefox", then only those two browsers would show up as columns.
706 #[serde(rename = "dimensionFilterClauses")]
707 pub dimension_filter_clauses: Option<Vec<DimensionFilterClause>>,
708 /// A list of dimensions to show as pivot columns. A Pivot can have a maximum of 4 dimensions. Pivot dimensions are part of the restriction on the total number of dimensions allowed in the request.
709 pub dimensions: Option<Vec<Dimension>>,
710 /// Specifies the maximum number of groups to return. The default value is 10, also the maximum value is 1,000.
711 #[serde(rename = "maxGroupCount")]
712 pub max_group_count: Option<i32>,
713 /// The pivot metrics. Pivot metrics are part of the restriction on total number of metrics allowed in the request.
714 pub metrics: Option<Vec<Metric>>,
715 /// If k metrics were requested, then the response will contain some data-dependent multiple of k columns in the report. E.g., if you pivoted on the dimension `ga:browser` then you'd get k columns for "Firefox", k columns for "IE", k columns for "Chrome", etc. The ordering of the groups of columns is determined by descending order of "total" for the first of the k values. Ties are broken by lexicographic ordering of the first pivot dimension, then lexicographic ordering of the second pivot dimension, and so on. E.g., if the totals for the first value for Firefox, IE, and Chrome were 8, 2, 8, respectively, the order of columns would be Chrome, Firefox, IE. The following let you choose which of the groups of k columns are included in the response.
716 #[serde(rename = "startGroup")]
717 pub start_group: Option<i32>,
718}
719
720impl common::Part for Pivot {}
721
722/// The headers for each of the pivot sections defined in the request.
723///
724/// This type is not used in any activity, and only used as *part* of another schema.
725///
726#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
727#[serde_with::serde_as]
728#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
729pub struct PivotHeader {
730 /// A single pivot section header.
731 #[serde(rename = "pivotHeaderEntries")]
732 pub pivot_header_entries: Option<Vec<PivotHeaderEntry>>,
733 /// The total number of groups for this pivot.
734 #[serde(rename = "totalPivotGroupsCount")]
735 pub total_pivot_groups_count: Option<i32>,
736}
737
738impl common::Part for PivotHeader {}
739
740/// The headers for the each of the metric column corresponding to the metrics requested in the pivots section of the response.
741///
742/// This type is not used in any activity, and only used as *part* of another schema.
743///
744#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
745#[serde_with::serde_as]
746#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
747pub struct PivotHeaderEntry {
748 /// The name of the dimensions in the pivot response.
749 #[serde(rename = "dimensionNames")]
750 pub dimension_names: Option<Vec<String>>,
751 /// The values for the dimensions in the pivot.
752 #[serde(rename = "dimensionValues")]
753 pub dimension_values: Option<Vec<String>>,
754 /// The metric header for the metric in the pivot.
755 pub metric: Option<MetricHeaderEntry>,
756}
757
758impl common::Part for PivotHeaderEntry {}
759
760/// The metric values in the pivot region.
761///
762/// This type is not used in any activity, and only used as *part* of another schema.
763///
764#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
765#[serde_with::serde_as]
766#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
767pub struct PivotValueRegion {
768 /// The values of the metrics in each of the pivot regions.
769 pub values: Option<Vec<String>>,
770}
771
772impl common::Part for PivotValueRegion {}
773
774/// Details of the products in an e-commerce transaction.
775///
776/// This type is not used in any activity, and only used as *part* of another schema.
777///
778#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
779#[serde_with::serde_as]
780#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
781pub struct ProductData {
782 /// The total revenue from purchased product items.
783 #[serde(rename = "itemRevenue")]
784 pub item_revenue: Option<f64>,
785 /// The product name, supplied by the e-commerce tracking application, for the purchased items.
786 #[serde(rename = "productName")]
787 pub product_name: Option<String>,
788 /// Total number of this product units in the transaction.
789 #[serde(rename = "productQuantity")]
790 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
791 pub product_quantity: Option<i64>,
792 /// Unique code that represents the product.
793 #[serde(rename = "productSku")]
794 pub product_sku: Option<String>,
795}
796
797impl common::Part for ProductData {}
798
799/// The data response corresponding to the request.
800///
801/// # Activities
802///
803/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
804/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
805///
806/// * [batch get reports](ReportBatchGetCall) (none)
807#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
808#[serde_with::serde_as]
809#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
810pub struct Report {
811 /// The column headers.
812 #[serde(rename = "columnHeader")]
813 pub column_header: Option<ColumnHeader>,
814 /// Response data.
815 pub data: Option<ReportData>,
816 /// Page token to retrieve the next page of results in the list.
817 #[serde(rename = "nextPageToken")]
818 pub next_page_token: Option<String>,
819}
820
821impl common::Resource for Report {}
822
823/// The data part of the report.
824///
825/// This type is not used in any activity, and only used as *part* of another schema.
826///
827#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
828#[serde_with::serde_as]
829#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
830pub struct ReportData {
831 /// The last time the data in the report was refreshed. All the hits received before this timestamp are included in the calculation of the report.
832 #[serde(rename = "dataLastRefreshed")]
833 pub data_last_refreshed: Option<chrono::DateTime<chrono::offset::Utc>>,
834 /// If empty reason is specified, the report is empty for this reason.
835 #[serde(rename = "emptyReason")]
836 pub empty_reason: Option<String>,
837 /// Indicates if response to this request is golden or not. Data is golden when the exact same request will not produce any new results if asked at a later point in time.
838 #[serde(rename = "isDataGolden")]
839 pub is_data_golden: Option<bool>,
840 /// Minimum and maximum values seen over all matching rows. These are both empty when `hideValueRanges` in the request is false, or when rowCount is zero.
841 pub maximums: Option<Vec<DateRangeValues>>,
842 /// Minimum and maximum values seen over all matching rows. These are both empty when `hideValueRanges` in the request is false, or when rowCount is zero.
843 pub minimums: Option<Vec<DateRangeValues>>,
844 /// Total number of matching rows for this query.
845 #[serde(rename = "rowCount")]
846 pub row_count: Option<i32>,
847 /// There's one ReportRow for every unique combination of dimensions.
848 pub rows: Option<Vec<ReportRow>>,
849 /// If the results are [sampled](https://support.google.com/analytics/answer/2637192), this returns the total number of samples read, one entry per date range. If the results are not sampled this field will not be defined. See [developer guide](https://developers.google.com/analytics/devguides/reporting/core/v4/basics#sampling) for details.
850 #[serde(rename = "samplesReadCounts")]
851 #[serde_as(as = "Option<Vec<serde_with::DisplayFromStr>>")]
852 pub samples_read_counts: Option<Vec<i64>>,
853 /// If the results are [sampled](https://support.google.com/analytics/answer/2637192), this returns the total number of samples present, one entry per date range. If the results are not sampled this field will not be defined. See [developer guide](https://developers.google.com/analytics/devguides/reporting/core/v4/basics#sampling) for details.
854 #[serde(rename = "samplingSpaceSizes")]
855 #[serde_as(as = "Option<Vec<serde_with::DisplayFromStr>>")]
856 pub sampling_space_sizes: Option<Vec<i64>>,
857 /// For each requested date range, for the set of all rows that match the query, every requested value format gets a total. The total for a value format is computed by first totaling the metrics mentioned in the value format and then evaluating the value format as a scalar expression. E.g., The "totals" for `3 / (ga:sessions + 2)` we compute `3 / ((sum of all relevant ga:sessions) + 2)`. Totals are computed before pagination.
858 pub totals: Option<Vec<DateRangeValues>>,
859}
860
861impl common::Part for ReportData {}
862
863/// The main request class which specifies the Reporting API request.
864///
865/// This type is not used in any activity, and only used as *part* of another schema.
866///
867#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
868#[serde_with::serde_as]
869#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
870pub struct ReportRequest {
871 /// Cohort group associated with this request. If there is a cohort group in the request the `ga:cohort` dimension must be present. Every [ReportRequest](#ReportRequest) within a `batchGet` method must contain the same `cohortGroup` definition.
872 #[serde(rename = "cohortGroup")]
873 pub cohort_group: Option<CohortGroup>,
874 /// Date ranges in the request. The request can have a maximum of 2 date ranges. The response will contain a set of metric values for each combination of the dimensions for each date range in the request. So, if there are two date ranges, there will be two set of metric values, one for the original date range and one for the second date range. The `reportRequest.dateRanges` field should not be specified for cohorts or Lifetime value requests. If a date range is not provided, the default date range is (startDate: current date - 7 days, endDate: current date - 1 day). Every [ReportRequest](#ReportRequest) within a `batchGet` method must contain the same `dateRanges` definition.
875 #[serde(rename = "dateRanges")]
876 pub date_ranges: Option<Vec<DateRange>>,
877 /// The dimension filter clauses for filtering Dimension Values. They are logically combined with the `AND` operator. Note that filtering occurs before any dimensions are aggregated, so that the returned metrics represent the total for only the relevant dimensions.
878 #[serde(rename = "dimensionFilterClauses")]
879 pub dimension_filter_clauses: Option<Vec<DimensionFilterClause>>,
880 /// The dimensions requested. Requests can have a total of 9 dimensions.
881 pub dimensions: Option<Vec<Dimension>>,
882 /// Dimension or metric filters that restrict the data returned for your request. To use the `filtersExpression`, supply a dimension or metric on which to filter, followed by the filter expression. For example, the following expression selects `ga:browser` dimension which starts with Firefox; `ga:browser=~^Firefox`. For more information on dimensions and metric filters, see [Filters reference](https://developers.google.com/analytics/devguides/reporting/core/v3/reference#filters).
883 #[serde(rename = "filtersExpression")]
884 pub filters_expression: Option<String>,
885 /// If set to true, hides the total of all metrics for all the matching rows, for every date range. The default false and will return the totals.
886 #[serde(rename = "hideTotals")]
887 pub hide_totals: Option<bool>,
888 /// If set to true, hides the minimum and maximum across all matching rows. The default is false and the value ranges are returned.
889 #[serde(rename = "hideValueRanges")]
890 pub hide_value_ranges: Option<bool>,
891 /// If set to false, the response does not include rows if all the retrieved metrics are equal to zero. The default is false which will exclude these rows.
892 #[serde(rename = "includeEmptyRows")]
893 pub include_empty_rows: Option<bool>,
894 /// The metric filter clauses. They are logically combined with the `AND` operator. Metric filters look at only the first date range and not the comparing date range. Note that filtering on metrics occurs after the metrics are aggregated.
895 #[serde(rename = "metricFilterClauses")]
896 pub metric_filter_clauses: Option<Vec<MetricFilterClause>>,
897 /// The metrics requested. Requests must specify at least one metric. Requests can have a total of 10 metrics.
898 pub metrics: Option<Vec<Metric>>,
899 /// Sort order on output rows. To compare two rows, the elements of the following are applied in order until a difference is found. All date ranges in the output get the same row order.
900 #[serde(rename = "orderBys")]
901 pub order_bys: Option<Vec<OrderBy>>,
902 /// Page size is for paging and specifies the maximum number of returned rows. Page size should be >= 0. A query returns the default of 1,000 rows. The Analytics Core Reporting API returns a maximum of 100,000 rows per request, no matter how many you ask for. It can also return fewer rows than requested, if there aren't as many dimension segments as you expect. For instance, there are fewer than 300 possible values for `ga:country`, so when segmenting only by country, you can't get more than 300 rows, even if you set `pageSize` to a higher value.
903 #[serde(rename = "pageSize")]
904 pub page_size: Option<i32>,
905 /// A continuation token to get the next page of the results. Adding this to the request will return the rows after the pageToken. The pageToken should be the value returned in the nextPageToken parameter in the response to the GetReports request.
906 #[serde(rename = "pageToken")]
907 pub page_token: Option<String>,
908 /// The pivot definitions. Requests can have a maximum of 2 pivots.
909 pub pivots: Option<Vec<Pivot>>,
910 /// The desired report [sample](https://support.google.com/analytics/answer/2637192) size. If the the `samplingLevel` field is unspecified the `DEFAULT` sampling level is used. Every [ReportRequest](#ReportRequest) within a `batchGet` method must contain the same `samplingLevel` definition. See [developer guide](https://developers.google.com/analytics/devguides/reporting/core/v4/basics#sampling) for details.
911 #[serde(rename = "samplingLevel")]
912 pub sampling_level: Option<String>,
913 /// Segment the data returned for the request. A segment definition helps look at a subset of the segment request. A request can contain up to four segments. Every [ReportRequest](#ReportRequest) within a `batchGet` method must contain the same `segments` definition. Requests with segments must have the `ga:segment` dimension.
914 pub segments: Option<Vec<Segment>>,
915 /// The Analytics [view ID](https://support.google.com/analytics/answer/1009618) from which to retrieve data. Every [ReportRequest](#ReportRequest) within a `batchGet` method must contain the same `viewId`.
916 #[serde(rename = "viewId")]
917 pub view_id: Option<String>,
918}
919
920impl common::Part for ReportRequest {}
921
922/// A row in the report.
923///
924/// This type is not used in any activity, and only used as *part* of another schema.
925///
926#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
927#[serde_with::serde_as]
928#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
929pub struct ReportRow {
930 /// List of requested dimensions.
931 pub dimensions: Option<Vec<String>>,
932 /// List of metrics for each requested DateRange.
933 pub metrics: Option<Vec<DateRangeValues>>,
934}
935
936impl common::Part for ReportRow {}
937
938/// The resource quota tokens remaining for the property after the request is completed.
939///
940/// This type is not used in any activity, and only used as *part* of another schema.
941///
942#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
943#[serde_with::serde_as]
944#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
945pub struct ResourceQuotasRemaining {
946 /// Daily resource quota remaining remaining.
947 #[serde(rename = "dailyQuotaTokensRemaining")]
948 pub daily_quota_tokens_remaining: Option<i32>,
949 /// Hourly resource quota tokens remaining.
950 #[serde(rename = "hourlyQuotaTokensRemaining")]
951 pub hourly_quota_tokens_remaining: Option<i32>,
952}
953
954impl common::Part for ResourceQuotasRemaining {}
955
956/// There is no detailed description.
957///
958/// This type is not used in any activity, and only used as *part* of another schema.
959///
960#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
961#[serde_with::serde_as]
962#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
963pub struct ScreenviewData {
964 /// The application name.
965 #[serde(rename = "appName")]
966 pub app_name: Option<String>,
967 /// Mobile manufacturer or branded name. Eg: "Google", "Apple" etc.
968 #[serde(rename = "mobileDeviceBranding")]
969 pub mobile_device_branding: Option<String>,
970 /// Mobile device model. Eg: "Pixel", "iPhone" etc.
971 #[serde(rename = "mobileDeviceModel")]
972 pub mobile_device_model: Option<String>,
973 /// The name of the screen.
974 #[serde(rename = "screenName")]
975 pub screen_name: Option<String>,
976}
977
978impl common::Part for ScreenviewData {}
979
980/// The request to fetch User Report from Reporting API `userActivity:get` call.
981///
982/// # Activities
983///
984/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
985/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
986///
987/// * [search user activity](UserActivitySearchCall) (request)
988#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
989#[serde_with::serde_as]
990#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
991pub struct SearchUserActivityRequest {
992 /// Set of all activity types being requested. Only acvities matching these types will be returned in the response. If empty, all activies will be returned.
993 #[serde(rename = "activityTypes")]
994 pub activity_types: Option<Vec<String>>,
995 /// Date range for which to retrieve the user activity. If a date range is not provided, the default date range is (startDate: current date - 7 days, endDate: current date - 1 day).
996 #[serde(rename = "dateRange")]
997 pub date_range: Option<DateRange>,
998 /// Page size is for paging and specifies the maximum number of returned rows. Page size should be > 0. If the value is 0 or if the field isn't specified, the request returns the default of 1000 rows per page.
999 #[serde(rename = "pageSize")]
1000 pub page_size: Option<i32>,
1001 /// A continuation token to get the next page of the results. Adding this to the request will return the rows after the pageToken. The pageToken should be the value returned in the nextPageToken parameter in the response to the [SearchUserActivityRequest](#SearchUserActivityRequest) request.
1002 #[serde(rename = "pageToken")]
1003 pub page_token: Option<String>,
1004 /// Required. Unique user Id to query for. Every [SearchUserActivityRequest](#SearchUserActivityRequest) must contain this field.
1005 pub user: Option<User>,
1006 /// Required. The Analytics [view ID](https://support.google.com/analytics/answer/1009618) from which to retrieve data. Every [SearchUserActivityRequest](#SearchUserActivityRequest) must contain the `viewId`.
1007 #[serde(rename = "viewId")]
1008 pub view_id: Option<String>,
1009}
1010
1011impl common::RequestValue for SearchUserActivityRequest {}
1012
1013/// The response from `userActivity:get` call.
1014///
1015/// # Activities
1016///
1017/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
1018/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
1019///
1020/// * [search user activity](UserActivitySearchCall) (response)
1021#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1022#[serde_with::serde_as]
1023#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1024pub struct SearchUserActivityResponse {
1025 /// This token should be passed to [SearchUserActivityRequest](#SearchUserActivityRequest) to retrieve the next page.
1026 #[serde(rename = "nextPageToken")]
1027 pub next_page_token: Option<String>,
1028 /// This field represents the [sampling rate](https://support.google.com/analytics/answer/2637192) for the given request and is a number between 0.0 to 1.0. See [developer guide](https://developers.google.com/analytics/devguides/reporting/core/v4/basics#sampling) for details.
1029 #[serde(rename = "sampleRate")]
1030 pub sample_rate: Option<f64>,
1031 /// Each record represents a session (device details, duration, etc).
1032 pub sessions: Option<Vec<UserActivitySession>>,
1033 /// Total rows returned by this query (across different pages).
1034 #[serde(rename = "totalRows")]
1035 pub total_rows: Option<i32>,
1036}
1037
1038impl common::ResponseResult for SearchUserActivityResponse {}
1039
1040/// The segment definition, if the report needs to be segmented. A Segment is a subset of the Analytics data. For example, of the entire set of users, one Segment might be users from a particular country or city.
1041///
1042/// This type is not used in any activity, and only used as *part* of another schema.
1043///
1044#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1045#[serde_with::serde_as]
1046#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1047pub struct Segment {
1048 /// A dynamic segment definition in the request.
1049 #[serde(rename = "dynamicSegment")]
1050 pub dynamic_segment: Option<DynamicSegment>,
1051 /// The segment ID of a built-in or custom segment, for example `gaid::-3`.
1052 #[serde(rename = "segmentId")]
1053 pub segment_id: Option<String>,
1054}
1055
1056impl common::Part for Segment {}
1057
1058/// SegmentDefinition defines the segment to be a set of SegmentFilters which are combined together with a logical `AND` operation.
1059///
1060/// This type is not used in any activity, and only used as *part* of another schema.
1061///
1062#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1063#[serde_with::serde_as]
1064#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1065pub struct SegmentDefinition {
1066 /// A segment is defined by a set of segment filters which are combined together with a logical `AND` operation.
1067 #[serde(rename = "segmentFilters")]
1068 pub segment_filters: Option<Vec<SegmentFilter>>,
1069}
1070
1071impl common::Part for SegmentDefinition {}
1072
1073/// Dimension filter specifies the filtering options on a dimension.
1074///
1075/// This type is not used in any activity, and only used as *part* of another schema.
1076///
1077#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1078#[serde_with::serde_as]
1079#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1080pub struct SegmentDimensionFilter {
1081 /// Should the match be case sensitive, ignored for `IN_LIST` operator.
1082 #[serde(rename = "caseSensitive")]
1083 pub case_sensitive: Option<bool>,
1084 /// Name of the dimension for which the filter is being applied.
1085 #[serde(rename = "dimensionName")]
1086 pub dimension_name: Option<String>,
1087 /// The list of expressions, only the first element is used for all operators
1088 pub expressions: Option<Vec<String>>,
1089 /// Maximum comparison values for `BETWEEN` match type.
1090 #[serde(rename = "maxComparisonValue")]
1091 pub max_comparison_value: Option<String>,
1092 /// Minimum comparison values for `BETWEEN` match type.
1093 #[serde(rename = "minComparisonValue")]
1094 pub min_comparison_value: Option<String>,
1095 /// The operator to use to match the dimension with the expressions.
1096 pub operator: Option<String>,
1097}
1098
1099impl common::Part for SegmentDimensionFilter {}
1100
1101/// SegmentFilter defines the segment to be either a simple or a sequence segment. A simple segment condition contains dimension and metric conditions to select the sessions or users. A sequence segment condition can be used to select users or sessions based on sequential conditions.
1102///
1103/// This type is not used in any activity, and only used as *part* of another schema.
1104///
1105#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1106#[serde_with::serde_as]
1107#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1108pub struct SegmentFilter {
1109 /// If true, match the complement of simple or sequence segment. For example, to match all visits not from "New York", we can define the segment as follows: "sessionSegment": { "segmentFilters": [{ "simpleSegment" :{ "orFiltersForSegment": [{ "segmentFilterClauses":[{ "dimensionFilter": { "dimensionName": "ga:city", "expressions": ["New York"] } }] }] }, "not": "True" }] },
1110 pub not: Option<bool>,
1111 /// Sequence conditions consist of one or more steps, where each step is defined by one or more dimension/metric conditions. Multiple steps can be combined with special sequence operators.
1112 #[serde(rename = "sequenceSegment")]
1113 pub sequence_segment: Option<SequenceSegment>,
1114 /// A Simple segment conditions consist of one or more dimension/metric conditions that can be combined
1115 #[serde(rename = "simpleSegment")]
1116 pub simple_segment: Option<SimpleSegment>,
1117}
1118
1119impl common::Part for SegmentFilter {}
1120
1121/// Filter Clause to be used in a segment definition, can be wither a metric or a dimension filter.
1122///
1123/// This type is not used in any activity, and only used as *part* of another schema.
1124///
1125#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1126#[serde_with::serde_as]
1127#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1128pub struct SegmentFilterClause {
1129 /// Dimension Filter for the segment definition.
1130 #[serde(rename = "dimensionFilter")]
1131 pub dimension_filter: Option<SegmentDimensionFilter>,
1132 /// Metric Filter for the segment definition.
1133 #[serde(rename = "metricFilter")]
1134 pub metric_filter: Option<SegmentMetricFilter>,
1135 /// Matches the complement (`!`) of the filter.
1136 pub not: Option<bool>,
1137}
1138
1139impl common::Part for SegmentFilterClause {}
1140
1141/// Metric filter to be used in a segment filter clause.
1142///
1143/// This type is not used in any activity, and only used as *part* of another schema.
1144///
1145#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1146#[serde_with::serde_as]
1147#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1148pub struct SegmentMetricFilter {
1149 /// The value to compare against. If the operator is `BETWEEN`, this value is treated as minimum comparison value.
1150 #[serde(rename = "comparisonValue")]
1151 pub comparison_value: Option<String>,
1152 /// Max comparison value is only used for `BETWEEN` operator.
1153 #[serde(rename = "maxComparisonValue")]
1154 pub max_comparison_value: Option<String>,
1155 /// The metric that will be filtered on. A `metricFilter` must contain a metric name.
1156 #[serde(rename = "metricName")]
1157 pub metric_name: Option<String>,
1158 /// Specifies is the operation to perform to compare the metric. The default is `EQUAL`.
1159 pub operator: Option<String>,
1160 /// Scope for a metric defines the level at which that metric is defined. The specified metric scope must be equal to or greater than its primary scope as defined in the data model. The primary scope is defined by if the segment is selecting users or sessions.
1161 pub scope: Option<String>,
1162}
1163
1164impl common::Part for SegmentMetricFilter {}
1165
1166/// A segment sequence definition.
1167///
1168/// This type is not used in any activity, and only used as *part* of another schema.
1169///
1170#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1171#[serde_with::serde_as]
1172#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1173pub struct SegmentSequenceStep {
1174 /// Specifies if the step immediately precedes or can be any time before the next step.
1175 #[serde(rename = "matchType")]
1176 pub match_type: Option<String>,
1177 /// A sequence is specified with a list of Or grouped filters which are combined with `AND` operator.
1178 #[serde(rename = "orFiltersForSegment")]
1179 pub or_filters_for_segment: Option<Vec<OrFiltersForSegment>>,
1180}
1181
1182impl common::Part for SegmentSequenceStep {}
1183
1184/// Sequence conditions consist of one or more steps, where each step is defined by one or more dimension/metric conditions. Multiple steps can be combined with special sequence operators.
1185///
1186/// This type is not used in any activity, and only used as *part* of another schema.
1187///
1188#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1189#[serde_with::serde_as]
1190#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1191pub struct SequenceSegment {
1192 /// If set, first step condition must match the first hit of the visitor (in the date range).
1193 #[serde(rename = "firstStepShouldMatchFirstHit")]
1194 pub first_step_should_match_first_hit: Option<bool>,
1195 /// The list of steps in the sequence.
1196 #[serde(rename = "segmentSequenceSteps")]
1197 pub segment_sequence_steps: Option<Vec<SegmentSequenceStep>>,
1198}
1199
1200impl common::Part for SequenceSegment {}
1201
1202/// A Simple segment conditions consist of one or more dimension/metric conditions that can be combined.
1203///
1204/// This type is not used in any activity, and only used as *part* of another schema.
1205///
1206#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1207#[serde_with::serde_as]
1208#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1209pub struct SimpleSegment {
1210 /// A list of segment filters groups which are combined with logical `AND` operator.
1211 #[serde(rename = "orFiltersForSegment")]
1212 pub or_filters_for_segment: Option<Vec<OrFiltersForSegment>>,
1213}
1214
1215impl common::Part for SimpleSegment {}
1216
1217/// Represents details collected when the visitor performs a transaction on the page.
1218///
1219/// This type is not used in any activity, and only used as *part* of another schema.
1220///
1221#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1222#[serde_with::serde_as]
1223#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1224pub struct TransactionData {
1225 /// The transaction ID, supplied by the e-commerce tracking method, for the purchase in the shopping cart.
1226 #[serde(rename = "transactionId")]
1227 pub transaction_id: Option<String>,
1228 /// The total sale revenue (excluding shipping and tax) of the transaction.
1229 #[serde(rename = "transactionRevenue")]
1230 pub transaction_revenue: Option<f64>,
1231 /// Total cost of shipping.
1232 #[serde(rename = "transactionShipping")]
1233 pub transaction_shipping: Option<f64>,
1234 /// Total tax for the transaction.
1235 #[serde(rename = "transactionTax")]
1236 pub transaction_tax: Option<f64>,
1237}
1238
1239impl common::Part for TransactionData {}
1240
1241/// Contains information to identify a particular user uniquely.
1242///
1243/// This type is not used in any activity, and only used as *part* of another schema.
1244///
1245#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1246#[serde_with::serde_as]
1247#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1248pub struct User {
1249 /// Type of the user in the request. The field `userId` is associated with this type.
1250 #[serde(rename = "type")]
1251 pub type_: Option<String>,
1252 /// Unique Id of the user for which the data is being requested.
1253 #[serde(rename = "userId")]
1254 pub user_id: Option<String>,
1255}
1256
1257impl common::Part for User {}
1258
1259/// This represents a user session performed on a specific device at a certain time over a period of time.
1260///
1261/// This type is not used in any activity, and only used as *part* of another schema.
1262///
1263#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
1264#[serde_with::serde_as]
1265#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
1266pub struct UserActivitySession {
1267 /// Represents a detailed view into each of the activity in this session.
1268 pub activities: Option<Vec<Activity>>,
1269 /// The data source of a hit. By default, hits sent from analytics.js are reported as "web" and hits sent from the mobile SDKs are reported as "app". These values can be overridden in the Measurement Protocol.
1270 #[serde(rename = "dataSource")]
1271 pub data_source: Option<String>,
1272 /// The type of device used: "mobile", "tablet" etc.
1273 #[serde(rename = "deviceCategory")]
1274 pub device_category: Option<String>,
1275 /// Platform on which the activity happened: "android", "ios" etc.
1276 pub platform: Option<String>,
1277 /// Date of this session in ISO-8601 format.
1278 #[serde(rename = "sessionDate")]
1279 pub session_date: Option<String>,
1280 /// Unique ID of the session.
1281 #[serde(rename = "sessionId")]
1282 pub session_id: Option<String>,
1283}
1284
1285impl common::Part for UserActivitySession {}
1286
1287// ###################
1288// MethodBuilders ###
1289// #################
1290
1291/// A builder providing access to all methods supported on *report* resources.
1292/// It is not used directly, but through the [`AnalyticsReporting`] hub.
1293///
1294/// # Example
1295///
1296/// Instantiate a resource builder
1297///
1298/// ```test_harness,no_run
1299/// extern crate hyper;
1300/// extern crate hyper_rustls;
1301/// extern crate google_analyticsreporting4 as analyticsreporting4;
1302///
1303/// # async fn dox() {
1304/// use analyticsreporting4::{AnalyticsReporting, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1305///
1306/// let secret: yup_oauth2::ApplicationSecret = Default::default();
1307/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1308/// secret,
1309/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1310/// ).build().await.unwrap();
1311///
1312/// let client = hyper_util::client::legacy::Client::builder(
1313/// hyper_util::rt::TokioExecutor::new()
1314/// )
1315/// .build(
1316/// hyper_rustls::HttpsConnectorBuilder::new()
1317/// .with_native_roots()
1318/// .unwrap()
1319/// .https_or_http()
1320/// .enable_http1()
1321/// .build()
1322/// );
1323/// let mut hub = AnalyticsReporting::new(client, auth);
1324/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
1325/// // like `batch_get(...)`
1326/// // to build up your call.
1327/// let rb = hub.reports();
1328/// # }
1329/// ```
1330pub struct ReportMethods<'a, C>
1331where
1332 C: 'a,
1333{
1334 hub: &'a AnalyticsReporting<C>,
1335}
1336
1337impl<'a, C> common::MethodsBuilder for ReportMethods<'a, C> {}
1338
1339impl<'a, C> ReportMethods<'a, C> {
1340 /// Create a builder to help you perform the following task:
1341 ///
1342 /// Returns the Analytics data.
1343 ///
1344 /// # Arguments
1345 ///
1346 /// * `request` - No description provided.
1347 pub fn batch_get(&self, request: GetReportsRequest) -> ReportBatchGetCall<'a, C> {
1348 ReportBatchGetCall {
1349 hub: self.hub,
1350 _request: request,
1351 _delegate: Default::default(),
1352 _additional_params: Default::default(),
1353 _scopes: Default::default(),
1354 }
1355 }
1356}
1357
1358/// A builder providing access to all methods supported on *userActivity* resources.
1359/// It is not used directly, but through the [`AnalyticsReporting`] hub.
1360///
1361/// # Example
1362///
1363/// Instantiate a resource builder
1364///
1365/// ```test_harness,no_run
1366/// extern crate hyper;
1367/// extern crate hyper_rustls;
1368/// extern crate google_analyticsreporting4 as analyticsreporting4;
1369///
1370/// # async fn dox() {
1371/// use analyticsreporting4::{AnalyticsReporting, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1372///
1373/// let secret: yup_oauth2::ApplicationSecret = Default::default();
1374/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1375/// secret,
1376/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1377/// ).build().await.unwrap();
1378///
1379/// let client = hyper_util::client::legacy::Client::builder(
1380/// hyper_util::rt::TokioExecutor::new()
1381/// )
1382/// .build(
1383/// hyper_rustls::HttpsConnectorBuilder::new()
1384/// .with_native_roots()
1385/// .unwrap()
1386/// .https_or_http()
1387/// .enable_http1()
1388/// .build()
1389/// );
1390/// let mut hub = AnalyticsReporting::new(client, auth);
1391/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
1392/// // like `search(...)`
1393/// // to build up your call.
1394/// let rb = hub.user_activity();
1395/// # }
1396/// ```
1397pub struct UserActivityMethods<'a, C>
1398where
1399 C: 'a,
1400{
1401 hub: &'a AnalyticsReporting<C>,
1402}
1403
1404impl<'a, C> common::MethodsBuilder for UserActivityMethods<'a, C> {}
1405
1406impl<'a, C> UserActivityMethods<'a, C> {
1407 /// Create a builder to help you perform the following task:
1408 ///
1409 /// Returns User Activity data.
1410 ///
1411 /// # Arguments
1412 ///
1413 /// * `request` - No description provided.
1414 pub fn search(&self, request: SearchUserActivityRequest) -> UserActivitySearchCall<'a, C> {
1415 UserActivitySearchCall {
1416 hub: self.hub,
1417 _request: request,
1418 _delegate: Default::default(),
1419 _additional_params: Default::default(),
1420 _scopes: Default::default(),
1421 }
1422 }
1423}
1424
1425// ###################
1426// CallBuilders ###
1427// #################
1428
1429/// Returns the Analytics data.
1430///
1431/// A builder for the *batchGet* method supported by a *report* resource.
1432/// It is not used directly, but through a [`ReportMethods`] instance.
1433///
1434/// # Example
1435///
1436/// Instantiate a resource method builder
1437///
1438/// ```test_harness,no_run
1439/// # extern crate hyper;
1440/// # extern crate hyper_rustls;
1441/// # extern crate google_analyticsreporting4 as analyticsreporting4;
1442/// use analyticsreporting4::api::GetReportsRequest;
1443/// # async fn dox() {
1444/// # use analyticsreporting4::{AnalyticsReporting, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1445///
1446/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1447/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1448/// # secret,
1449/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1450/// # ).build().await.unwrap();
1451///
1452/// # let client = hyper_util::client::legacy::Client::builder(
1453/// # hyper_util::rt::TokioExecutor::new()
1454/// # )
1455/// # .build(
1456/// # hyper_rustls::HttpsConnectorBuilder::new()
1457/// # .with_native_roots()
1458/// # .unwrap()
1459/// # .https_or_http()
1460/// # .enable_http1()
1461/// # .build()
1462/// # );
1463/// # let mut hub = AnalyticsReporting::new(client, auth);
1464/// // As the method needs a request, you would usually fill it with the desired information
1465/// // into the respective structure. Some of the parts shown here might not be applicable !
1466/// // Values shown here are possibly random and not representative !
1467/// let mut req = GetReportsRequest::default();
1468///
1469/// // You can configure optional parameters by calling the respective setters at will, and
1470/// // execute the final call using `doit()`.
1471/// // Values shown here are possibly random and not representative !
1472/// let result = hub.reports().batch_get(req)
1473/// .doit().await;
1474/// # }
1475/// ```
1476pub struct ReportBatchGetCall<'a, C>
1477where
1478 C: 'a,
1479{
1480 hub: &'a AnalyticsReporting<C>,
1481 _request: GetReportsRequest,
1482 _delegate: Option<&'a mut dyn common::Delegate>,
1483 _additional_params: HashMap<String, String>,
1484 _scopes: BTreeSet<String>,
1485}
1486
1487impl<'a, C> common::CallBuilder for ReportBatchGetCall<'a, C> {}
1488
1489impl<'a, C> ReportBatchGetCall<'a, C>
1490where
1491 C: common::Connector,
1492{
1493 /// Perform the operation you have build so far.
1494 pub async fn doit(mut self) -> common::Result<(common::Response, GetReportsResponse)> {
1495 use std::borrow::Cow;
1496 use std::io::{Read, Seek};
1497
1498 use common::{url::Params, ToParts};
1499 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1500
1501 let mut dd = common::DefaultDelegate;
1502 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1503 dlg.begin(common::MethodInfo {
1504 id: "analyticsreporting.reports.batchGet",
1505 http_method: hyper::Method::POST,
1506 });
1507
1508 for &field in ["alt"].iter() {
1509 if self._additional_params.contains_key(field) {
1510 dlg.finished(false);
1511 return Err(common::Error::FieldClash(field));
1512 }
1513 }
1514
1515 let mut params = Params::with_capacity(3 + self._additional_params.len());
1516
1517 params.extend(self._additional_params.iter());
1518
1519 params.push("alt", "json");
1520 let mut url = self.hub._base_url.clone() + "v4/reports:batchGet";
1521 if self._scopes.is_empty() {
1522 self._scopes.insert(Scope::Analytic.as_ref().to_string());
1523 }
1524
1525 let url = params.parse_with_url(&url);
1526
1527 let mut json_mime_type = mime::APPLICATION_JSON;
1528 let mut request_value_reader = {
1529 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1530 common::remove_json_null_values(&mut value);
1531 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1532 serde_json::to_writer(&mut dst, &value).unwrap();
1533 dst
1534 };
1535 let request_size = request_value_reader
1536 .seek(std::io::SeekFrom::End(0))
1537 .unwrap();
1538 request_value_reader
1539 .seek(std::io::SeekFrom::Start(0))
1540 .unwrap();
1541
1542 loop {
1543 let token = match self
1544 .hub
1545 .auth
1546 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1547 .await
1548 {
1549 Ok(token) => token,
1550 Err(e) => match dlg.token(e) {
1551 Ok(token) => token,
1552 Err(e) => {
1553 dlg.finished(false);
1554 return Err(common::Error::MissingToken(e));
1555 }
1556 },
1557 };
1558 request_value_reader
1559 .seek(std::io::SeekFrom::Start(0))
1560 .unwrap();
1561 let mut req_result = {
1562 let client = &self.hub.client;
1563 dlg.pre_request();
1564 let mut req_builder = hyper::Request::builder()
1565 .method(hyper::Method::POST)
1566 .uri(url.as_str())
1567 .header(USER_AGENT, self.hub._user_agent.clone());
1568
1569 if let Some(token) = token.as_ref() {
1570 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1571 }
1572
1573 let request = req_builder
1574 .header(CONTENT_TYPE, json_mime_type.to_string())
1575 .header(CONTENT_LENGTH, request_size as u64)
1576 .body(common::to_body(
1577 request_value_reader.get_ref().clone().into(),
1578 ));
1579
1580 client.request(request.unwrap()).await
1581 };
1582
1583 match req_result {
1584 Err(err) => {
1585 if let common::Retry::After(d) = dlg.http_error(&err) {
1586 sleep(d).await;
1587 continue;
1588 }
1589 dlg.finished(false);
1590 return Err(common::Error::HttpError(err));
1591 }
1592 Ok(res) => {
1593 let (mut parts, body) = res.into_parts();
1594 let mut body = common::Body::new(body);
1595 if !parts.status.is_success() {
1596 let bytes = common::to_bytes(body).await.unwrap_or_default();
1597 let error = serde_json::from_str(&common::to_string(&bytes));
1598 let response = common::to_response(parts, bytes.into());
1599
1600 if let common::Retry::After(d) =
1601 dlg.http_failure(&response, error.as_ref().ok())
1602 {
1603 sleep(d).await;
1604 continue;
1605 }
1606
1607 dlg.finished(false);
1608
1609 return Err(match error {
1610 Ok(value) => common::Error::BadRequest(value),
1611 _ => common::Error::Failure(response),
1612 });
1613 }
1614 let response = {
1615 let bytes = common::to_bytes(body).await.unwrap_or_default();
1616 let encoded = common::to_string(&bytes);
1617 match serde_json::from_str(&encoded) {
1618 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1619 Err(error) => {
1620 dlg.response_json_decode_error(&encoded, &error);
1621 return Err(common::Error::JsonDecodeError(
1622 encoded.to_string(),
1623 error,
1624 ));
1625 }
1626 }
1627 };
1628
1629 dlg.finished(true);
1630 return Ok(response);
1631 }
1632 }
1633 }
1634 }
1635
1636 ///
1637 /// Sets the *request* property to the given value.
1638 ///
1639 /// Even though the property as already been set when instantiating this call,
1640 /// we provide this method for API completeness.
1641 pub fn request(mut self, new_value: GetReportsRequest) -> ReportBatchGetCall<'a, C> {
1642 self._request = new_value;
1643 self
1644 }
1645 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1646 /// while executing the actual API request.
1647 ///
1648 /// ````text
1649 /// It should be used to handle progress information, and to implement a certain level of resilience.
1650 /// ````
1651 ///
1652 /// Sets the *delegate* property to the given value.
1653 pub fn delegate(
1654 mut self,
1655 new_value: &'a mut dyn common::Delegate,
1656 ) -> ReportBatchGetCall<'a, C> {
1657 self._delegate = Some(new_value);
1658 self
1659 }
1660
1661 /// Set any additional parameter of the query string used in the request.
1662 /// It should be used to set parameters which are not yet available through their own
1663 /// setters.
1664 ///
1665 /// Please note that this method must not be used to set any of the known parameters
1666 /// which have their own setter method. If done anyway, the request will fail.
1667 ///
1668 /// # Additional Parameters
1669 ///
1670 /// * *$.xgafv* (query-string) - V1 error format.
1671 /// * *access_token* (query-string) - OAuth access token.
1672 /// * *alt* (query-string) - Data format for response.
1673 /// * *callback* (query-string) - JSONP
1674 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1675 /// * *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.
1676 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1677 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1678 /// * *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.
1679 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1680 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1681 pub fn param<T>(mut self, name: T, value: T) -> ReportBatchGetCall<'a, C>
1682 where
1683 T: AsRef<str>,
1684 {
1685 self._additional_params
1686 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1687 self
1688 }
1689
1690 /// Identifies the authorization scope for the method you are building.
1691 ///
1692 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1693 /// [`Scope::Analytic`].
1694 ///
1695 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1696 /// tokens for more than one scope.
1697 ///
1698 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1699 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1700 /// sufficient, a read-write scope will do as well.
1701 pub fn add_scope<St>(mut self, scope: St) -> ReportBatchGetCall<'a, C>
1702 where
1703 St: AsRef<str>,
1704 {
1705 self._scopes.insert(String::from(scope.as_ref()));
1706 self
1707 }
1708 /// Identifies the authorization scope(s) for the method you are building.
1709 ///
1710 /// See [`Self::add_scope()`] for details.
1711 pub fn add_scopes<I, St>(mut self, scopes: I) -> ReportBatchGetCall<'a, C>
1712 where
1713 I: IntoIterator<Item = St>,
1714 St: AsRef<str>,
1715 {
1716 self._scopes
1717 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1718 self
1719 }
1720
1721 /// Removes all scopes, and no default scope will be used either.
1722 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1723 /// for details).
1724 pub fn clear_scopes(mut self) -> ReportBatchGetCall<'a, C> {
1725 self._scopes.clear();
1726 self
1727 }
1728}
1729
1730/// Returns User Activity data.
1731///
1732/// A builder for the *search* method supported by a *userActivity* resource.
1733/// It is not used directly, but through a [`UserActivityMethods`] instance.
1734///
1735/// # Example
1736///
1737/// Instantiate a resource method builder
1738///
1739/// ```test_harness,no_run
1740/// # extern crate hyper;
1741/// # extern crate hyper_rustls;
1742/// # extern crate google_analyticsreporting4 as analyticsreporting4;
1743/// use analyticsreporting4::api::SearchUserActivityRequest;
1744/// # async fn dox() {
1745/// # use analyticsreporting4::{AnalyticsReporting, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1746///
1747/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1748/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1749/// # secret,
1750/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1751/// # ).build().await.unwrap();
1752///
1753/// # let client = hyper_util::client::legacy::Client::builder(
1754/// # hyper_util::rt::TokioExecutor::new()
1755/// # )
1756/// # .build(
1757/// # hyper_rustls::HttpsConnectorBuilder::new()
1758/// # .with_native_roots()
1759/// # .unwrap()
1760/// # .https_or_http()
1761/// # .enable_http1()
1762/// # .build()
1763/// # );
1764/// # let mut hub = AnalyticsReporting::new(client, auth);
1765/// // As the method needs a request, you would usually fill it with the desired information
1766/// // into the respective structure. Some of the parts shown here might not be applicable !
1767/// // Values shown here are possibly random and not representative !
1768/// let mut req = SearchUserActivityRequest::default();
1769///
1770/// // You can configure optional parameters by calling the respective setters at will, and
1771/// // execute the final call using `doit()`.
1772/// // Values shown here are possibly random and not representative !
1773/// let result = hub.user_activity().search(req)
1774/// .doit().await;
1775/// # }
1776/// ```
1777pub struct UserActivitySearchCall<'a, C>
1778where
1779 C: 'a,
1780{
1781 hub: &'a AnalyticsReporting<C>,
1782 _request: SearchUserActivityRequest,
1783 _delegate: Option<&'a mut dyn common::Delegate>,
1784 _additional_params: HashMap<String, String>,
1785 _scopes: BTreeSet<String>,
1786}
1787
1788impl<'a, C> common::CallBuilder for UserActivitySearchCall<'a, C> {}
1789
1790impl<'a, C> UserActivitySearchCall<'a, C>
1791where
1792 C: common::Connector,
1793{
1794 /// Perform the operation you have build so far.
1795 pub async fn doit(mut self) -> common::Result<(common::Response, SearchUserActivityResponse)> {
1796 use std::borrow::Cow;
1797 use std::io::{Read, Seek};
1798
1799 use common::{url::Params, ToParts};
1800 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1801
1802 let mut dd = common::DefaultDelegate;
1803 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1804 dlg.begin(common::MethodInfo {
1805 id: "analyticsreporting.userActivity.search",
1806 http_method: hyper::Method::POST,
1807 });
1808
1809 for &field in ["alt"].iter() {
1810 if self._additional_params.contains_key(field) {
1811 dlg.finished(false);
1812 return Err(common::Error::FieldClash(field));
1813 }
1814 }
1815
1816 let mut params = Params::with_capacity(3 + self._additional_params.len());
1817
1818 params.extend(self._additional_params.iter());
1819
1820 params.push("alt", "json");
1821 let mut url = self.hub._base_url.clone() + "v4/userActivity:search";
1822 if self._scopes.is_empty() {
1823 self._scopes.insert(Scope::Analytic.as_ref().to_string());
1824 }
1825
1826 let url = params.parse_with_url(&url);
1827
1828 let mut json_mime_type = mime::APPLICATION_JSON;
1829 let mut request_value_reader = {
1830 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1831 common::remove_json_null_values(&mut value);
1832 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1833 serde_json::to_writer(&mut dst, &value).unwrap();
1834 dst
1835 };
1836 let request_size = request_value_reader
1837 .seek(std::io::SeekFrom::End(0))
1838 .unwrap();
1839 request_value_reader
1840 .seek(std::io::SeekFrom::Start(0))
1841 .unwrap();
1842
1843 loop {
1844 let token = match self
1845 .hub
1846 .auth
1847 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1848 .await
1849 {
1850 Ok(token) => token,
1851 Err(e) => match dlg.token(e) {
1852 Ok(token) => token,
1853 Err(e) => {
1854 dlg.finished(false);
1855 return Err(common::Error::MissingToken(e));
1856 }
1857 },
1858 };
1859 request_value_reader
1860 .seek(std::io::SeekFrom::Start(0))
1861 .unwrap();
1862 let mut req_result = {
1863 let client = &self.hub.client;
1864 dlg.pre_request();
1865 let mut req_builder = hyper::Request::builder()
1866 .method(hyper::Method::POST)
1867 .uri(url.as_str())
1868 .header(USER_AGENT, self.hub._user_agent.clone());
1869
1870 if let Some(token) = token.as_ref() {
1871 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1872 }
1873
1874 let request = req_builder
1875 .header(CONTENT_TYPE, json_mime_type.to_string())
1876 .header(CONTENT_LENGTH, request_size as u64)
1877 .body(common::to_body(
1878 request_value_reader.get_ref().clone().into(),
1879 ));
1880
1881 client.request(request.unwrap()).await
1882 };
1883
1884 match req_result {
1885 Err(err) => {
1886 if let common::Retry::After(d) = dlg.http_error(&err) {
1887 sleep(d).await;
1888 continue;
1889 }
1890 dlg.finished(false);
1891 return Err(common::Error::HttpError(err));
1892 }
1893 Ok(res) => {
1894 let (mut parts, body) = res.into_parts();
1895 let mut body = common::Body::new(body);
1896 if !parts.status.is_success() {
1897 let bytes = common::to_bytes(body).await.unwrap_or_default();
1898 let error = serde_json::from_str(&common::to_string(&bytes));
1899 let response = common::to_response(parts, bytes.into());
1900
1901 if let common::Retry::After(d) =
1902 dlg.http_failure(&response, error.as_ref().ok())
1903 {
1904 sleep(d).await;
1905 continue;
1906 }
1907
1908 dlg.finished(false);
1909
1910 return Err(match error {
1911 Ok(value) => common::Error::BadRequest(value),
1912 _ => common::Error::Failure(response),
1913 });
1914 }
1915 let response = {
1916 let bytes = common::to_bytes(body).await.unwrap_or_default();
1917 let encoded = common::to_string(&bytes);
1918 match serde_json::from_str(&encoded) {
1919 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1920 Err(error) => {
1921 dlg.response_json_decode_error(&encoded, &error);
1922 return Err(common::Error::JsonDecodeError(
1923 encoded.to_string(),
1924 error,
1925 ));
1926 }
1927 }
1928 };
1929
1930 dlg.finished(true);
1931 return Ok(response);
1932 }
1933 }
1934 }
1935 }
1936
1937 ///
1938 /// Sets the *request* property to the given value.
1939 ///
1940 /// Even though the property as already been set when instantiating this call,
1941 /// we provide this method for API completeness.
1942 pub fn request(
1943 mut self,
1944 new_value: SearchUserActivityRequest,
1945 ) -> UserActivitySearchCall<'a, C> {
1946 self._request = new_value;
1947 self
1948 }
1949 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1950 /// while executing the actual API request.
1951 ///
1952 /// ````text
1953 /// It should be used to handle progress information, and to implement a certain level of resilience.
1954 /// ````
1955 ///
1956 /// Sets the *delegate* property to the given value.
1957 pub fn delegate(
1958 mut self,
1959 new_value: &'a mut dyn common::Delegate,
1960 ) -> UserActivitySearchCall<'a, C> {
1961 self._delegate = Some(new_value);
1962 self
1963 }
1964
1965 /// Set any additional parameter of the query string used in the request.
1966 /// It should be used to set parameters which are not yet available through their own
1967 /// setters.
1968 ///
1969 /// Please note that this method must not be used to set any of the known parameters
1970 /// which have their own setter method. If done anyway, the request will fail.
1971 ///
1972 /// # Additional Parameters
1973 ///
1974 /// * *$.xgafv* (query-string) - V1 error format.
1975 /// * *access_token* (query-string) - OAuth access token.
1976 /// * *alt* (query-string) - Data format for response.
1977 /// * *callback* (query-string) - JSONP
1978 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1979 /// * *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.
1980 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1981 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1982 /// * *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.
1983 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1984 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1985 pub fn param<T>(mut self, name: T, value: T) -> UserActivitySearchCall<'a, C>
1986 where
1987 T: AsRef<str>,
1988 {
1989 self._additional_params
1990 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1991 self
1992 }
1993
1994 /// Identifies the authorization scope for the method you are building.
1995 ///
1996 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1997 /// [`Scope::Analytic`].
1998 ///
1999 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2000 /// tokens for more than one scope.
2001 ///
2002 /// Usually there is more than one suitable scope to authorize an operation, some of which may
2003 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2004 /// sufficient, a read-write scope will do as well.
2005 pub fn add_scope<St>(mut self, scope: St) -> UserActivitySearchCall<'a, C>
2006 where
2007 St: AsRef<str>,
2008 {
2009 self._scopes.insert(String::from(scope.as_ref()));
2010 self
2011 }
2012 /// Identifies the authorization scope(s) for the method you are building.
2013 ///
2014 /// See [`Self::add_scope()`] for details.
2015 pub fn add_scopes<I, St>(mut self, scopes: I) -> UserActivitySearchCall<'a, C>
2016 where
2017 I: IntoIterator<Item = St>,
2018 St: AsRef<str>,
2019 {
2020 self._scopes
2021 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2022 self
2023 }
2024
2025 /// Removes all scopes, and no default scope will be used either.
2026 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2027 /// for details).
2028 pub fn clear_scopes(mut self) -> UserActivitySearchCall<'a, C> {
2029 self._scopes.clear();
2030 self
2031 }
2032}