google_fcm1/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 /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
17 CloudPlatform,
18
19 /// Send messages and manage messaging subscriptions for your Firebase applications
20 FirebaseMessaging,
21}
22
23impl AsRef<str> for Scope {
24 fn as_ref(&self) -> &str {
25 match *self {
26 Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
27 Scope::FirebaseMessaging => "https://www.googleapis.com/auth/firebase.messaging",
28 }
29 }
30}
31
32#[allow(clippy::derivable_impls)]
33impl Default for Scope {
34 fn default() -> Scope {
35 Scope::CloudPlatform
36 }
37}
38
39// ########
40// HUB ###
41// ######
42
43/// Central instance to access all FirebaseCloudMessaging 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_fcm1 as fcm1;
53/// use fcm1::api::SendMessageRequest;
54/// use fcm1::{Result, Error};
55/// # async fn dox() {
56/// use fcm1::{FirebaseCloudMessaging, 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 connector = hyper_rustls::HttpsConnectorBuilder::new()
67/// .with_native_roots()
68/// .unwrap()
69/// .https_only()
70/// .enable_http2()
71/// .build();
72///
73/// let executor = hyper_util::rt::TokioExecutor::new();
74/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
75/// secret,
76/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
77/// yup_oauth2::client::CustomHyperClientBuilder::from(
78/// hyper_util::client::legacy::Client::builder(executor).build(connector),
79/// ),
80/// ).build().await.unwrap();
81///
82/// let client = hyper_util::client::legacy::Client::builder(
83/// hyper_util::rt::TokioExecutor::new()
84/// )
85/// .build(
86/// hyper_rustls::HttpsConnectorBuilder::new()
87/// .with_native_roots()
88/// .unwrap()
89/// .https_or_http()
90/// .enable_http2()
91/// .build()
92/// );
93/// let mut hub = FirebaseCloudMessaging::new(client, auth);
94/// // As the method needs a request, you would usually fill it with the desired information
95/// // into the respective structure. Some of the parts shown here might not be applicable !
96/// // Values shown here are possibly random and not representative !
97/// let mut req = SendMessageRequest::default();
98///
99/// // You can configure optional parameters by calling the respective setters at will, and
100/// // execute the final call using `doit()`.
101/// // Values shown here are possibly random and not representative !
102/// let result = hub.projects().messages_send(req, "parent")
103/// .doit().await;
104///
105/// match result {
106/// Err(e) => match e {
107/// // The Error enum provides details about what exactly happened.
108/// // You can also just use its `Debug`, `Display` or `Error` traits
109/// Error::HttpError(_)
110/// |Error::Io(_)
111/// |Error::MissingAPIKey
112/// |Error::MissingToken(_)
113/// |Error::Cancelled
114/// |Error::UploadSizeLimitExceeded(_, _)
115/// |Error::Failure(_)
116/// |Error::BadRequest(_)
117/// |Error::FieldClash(_)
118/// |Error::JsonDecodeError(_, _) => println!("{}", e),
119/// },
120/// Ok(res) => println!("Success: {:?}", res),
121/// }
122/// # }
123/// ```
124#[derive(Clone)]
125pub struct FirebaseCloudMessaging<C> {
126 pub client: common::Client<C>,
127 pub auth: Box<dyn common::GetToken>,
128 _user_agent: String,
129 _base_url: String,
130 _root_url: String,
131}
132
133impl<C> common::Hub for FirebaseCloudMessaging<C> {}
134
135impl<'a, C> FirebaseCloudMessaging<C> {
136 pub fn new<A: 'static + common::GetToken>(
137 client: common::Client<C>,
138 auth: A,
139 ) -> FirebaseCloudMessaging<C> {
140 FirebaseCloudMessaging {
141 client,
142 auth: Box::new(auth),
143 _user_agent: "google-api-rust-client/7.0.0".to_string(),
144 _base_url: "https://fcm.googleapis.com/".to_string(),
145 _root_url: "https://fcm.googleapis.com/".to_string(),
146 }
147 }
148
149 pub fn projects(&'a self) -> ProjectMethods<'a, C> {
150 ProjectMethods { hub: self }
151 }
152
153 /// Set the user-agent header field to use in all requests to the server.
154 /// It defaults to `google-api-rust-client/7.0.0`.
155 ///
156 /// Returns the previously set user-agent.
157 pub fn user_agent(&mut self, agent_name: String) -> String {
158 std::mem::replace(&mut self._user_agent, agent_name)
159 }
160
161 /// Set the base url to use in all requests to the server.
162 /// It defaults to `https://fcm.googleapis.com/`.
163 ///
164 /// Returns the previously set base url.
165 pub fn base_url(&mut self, new_base_url: String) -> String {
166 std::mem::replace(&mut self._base_url, new_base_url)
167 }
168
169 /// Set the root url to use in all requests to the server.
170 /// It defaults to `https://fcm.googleapis.com/`.
171 ///
172 /// Returns the previously set root url.
173 pub fn root_url(&mut self, new_root_url: String) -> String {
174 std::mem::replace(&mut self._root_url, new_root_url)
175 }
176}
177
178// ############
179// SCHEMAS ###
180// ##########
181/// Android specific options for messages sent through [FCM connection server](https://goo.gl/4GLdUl).
182///
183/// This type is not used in any activity, and only used as *part* of another schema.
184///
185#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
186#[serde_with::serde_as]
187#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
188pub struct AndroidConfig {
189 /// Optional. If set to true, messages will be allowed to be delivered to the app while the device is in bandwidth constrained mode. This should only be enabled when the app has been tested to properly handle messages in bandwidth constrained mode.
190 #[serde(rename = "bandwidthConstrainedOk")]
191 pub bandwidth_constrained_ok: Option<bool>,
192 /// An identifier of a group of messages that can be collapsed, so that only the last message gets sent when delivery can be resumed. A maximum of 4 different collapse keys is allowed at any given time.
193 #[serde(rename = "collapseKey")]
194 pub collapse_key: Option<String>,
195 /// Arbitrary key/value payload. If present, it will override google.firebase.fcm.v1.Message.data.
196 pub data: Option<HashMap<String, String>>,
197 /// Optional. If set to true, messages will be allowed to be delivered to the app while the device is in direct boot mode. See [Support Direct Boot mode](https://developer.android.com/training/articles/direct-boot).
198 #[serde(rename = "directBootOk")]
199 pub direct_boot_ok: Option<bool>,
200 /// Options for features provided by the FCM SDK for Android.
201 #[serde(rename = "fcmOptions")]
202 pub fcm_options: Option<AndroidFcmOptions>,
203 /// Notification to send to android devices.
204 pub notification: Option<AndroidNotification>,
205 /// Message priority. Can take "normal" and "high" values. For more information, see [Setting the priority of a message](https://goo.gl/GjONJv).
206 pub priority: Option<String>,
207 /// Package name of the application where the registration token must match in order to receive the message.
208 #[serde(rename = "restrictedPackageName")]
209 pub restricted_package_name: Option<String>,
210 /// Optional. If set to true, messages will be allowed to be delivered to the app while the device is connected over a restricted satellite network. This should only be enabled for messages that can be handled over a restricted satellite network and only for apps that are enabled to work over a restricted satellite network. Note that the ability of the app to connect to a restricted satellite network is dependent on the carrier's settings and the device model.
211 #[serde(rename = "restrictedSatelliteOk")]
212 pub restricted_satellite_ok: Option<bool>,
213 /// How long (in seconds) the message should be kept in FCM storage if the device is offline. The maximum time to live supported is 4 weeks, and the default value is 4 weeks if not set. Set it to 0 if want to send the message immediately. In JSON format, the Duration type is encoded as a string rather than an object, where the string ends in the suffix "s" (indicating seconds) and is preceded by the number of seconds, with nanoseconds expressed as fractional seconds. For example, 3 seconds with 0 nanoseconds should be encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should be expressed in JSON format as "3.000000001s". The ttl will be rounded down to the nearest second.
214 #[serde_as(as = "Option<common::serde::duration::Wrapper>")]
215 pub ttl: Option<chrono::Duration>,
216}
217
218impl common::Part for AndroidConfig {}
219
220/// Options for features provided by the FCM SDK for Android.
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 AndroidFcmOptions {
228 /// Label associated with the message's analytics data.
229 #[serde(rename = "analyticsLabel")]
230 pub analytics_label: Option<String>,
231}
232
233impl common::Part for AndroidFcmOptions {}
234
235/// Notification to send to android devices.
236///
237/// This type is not used in any activity, and only used as *part* of another schema.
238///
239#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
240#[serde_with::serde_as]
241#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
242pub struct AndroidNotification {
243 /// The notification's body text. If present, it will override google.firebase.fcm.v1.Notification.body.
244 pub body: Option<String>,
245 /// Variable string values to be used in place of the format specifiers in body_loc_key to use to localize the body text to the user's current localization. See [Formatting and Styling](https://goo.gl/MalYE3) for more information.
246 #[serde(rename = "bodyLocArgs")]
247 pub body_loc_args: Option<Vec<String>>,
248 /// The key to the body string in the app's string resources to use to localize the body text to the user's current localization. See [String Resources](https://goo.gl/NdFZGI) for more information.
249 #[serde(rename = "bodyLocKey")]
250 pub body_loc_key: Option<String>,
251 /// If set, display notifications delivered to the device will be handled by the app instead of the proxy.
252 #[serde(rename = "bypassProxyNotification")]
253 pub bypass_proxy_notification: Option<bool>,
254 /// The [notification's channel id](https://developer.android.com/guide/topics/ui/notifiers/notifications#ManageChannels) (new in Android O). The app must create a channel with this channel ID before any notification with this channel ID is received. If you don't send this channel ID in the request, or if the channel ID provided has not yet been created by the app, FCM uses the channel ID specified in the app manifest.
255 #[serde(rename = "channelId")]
256 pub channel_id: Option<String>,
257 /// The action associated with a user click on the notification. If specified, an activity with a matching intent filter is launched when a user clicks on the notification.
258 #[serde(rename = "clickAction")]
259 pub click_action: Option<String>,
260 /// The notification's icon color, expressed in #rrggbb format.
261 pub color: Option<String>,
262 /// If set to true, use the Android framework's default LED light settings for the notification. Default values are specified in [config.xml](https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/values/config.xml). If `default_light_settings` is set to true and `light_settings` is also set, the user-specified `light_settings` is used instead of the default value.
263 #[serde(rename = "defaultLightSettings")]
264 pub default_light_settings: Option<bool>,
265 /// If set to true, use the Android framework's default sound for the notification. Default values are specified in [config.xml](https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/values/config.xml).
266 #[serde(rename = "defaultSound")]
267 pub default_sound: Option<bool>,
268 /// If set to true, use the Android framework's default vibrate pattern for the notification. Default values are specified in [config.xml](https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/values/config.xml). If `default_vibrate_timings` is set to true and `vibrate_timings` is also set, the default value is used instead of the user-specified `vibrate_timings`.
269 #[serde(rename = "defaultVibrateTimings")]
270 pub default_vibrate_timings: Option<bool>,
271 /// Set the time that the event in the notification occurred. Notifications in the panel are sorted by this time. A point in time is represented using [protobuf.Timestamp](https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Timestamp).
272 #[serde(rename = "eventTime")]
273 pub event_time: Option<chrono::DateTime<chrono::offset::Utc>>,
274 /// The notification's icon. Sets the notification icon to myicon for drawable resource myicon. If you don't send this key in the request, FCM displays the launcher icon specified in your app manifest.
275 pub icon: Option<String>,
276 /// Contains the URL of an image that is going to be displayed in a notification. If present, it will override google.firebase.fcm.v1.Notification.image.
277 pub image: Option<String>,
278 /// Settings to control the notification's LED blinking rate and color if LED is available on the device. The total blinking time is controlled by the OS.
279 #[serde(rename = "lightSettings")]
280 pub light_settings: Option<LightSettings>,
281 /// Set whether or not this notification is relevant only to the current device. Some notifications can be bridged to other devices for remote display, such as a Wear OS watch. This hint can be set to recommend this notification not be bridged. See [Wear OS guides](https://developer.android.com/training/wearables/notifications/bridger#existing-method-of-preventing-bridging)
282 #[serde(rename = "localOnly")]
283 pub local_only: Option<bool>,
284 /// Sets the number of items this notification represents. May be displayed as a badge count for launchers that support badging.See [Notification Badge](https://developer.android.com/training/notify-user/badges). For example, this might be useful if you're using just one notification to represent multiple new messages but you want the count here to represent the number of total new messages. If zero or unspecified, systems that support badging use the default, which is to increment a number displayed on the long-press menu each time a new notification arrives.
285 #[serde(rename = "notificationCount")]
286 pub notification_count: Option<i32>,
287 /// Set the relative priority for this notification. Priority is an indication of how much of the user's attention should be consumed by this notification. Low-priority notifications may be hidden from the user in certain situations, while the user might be interrupted for a higher-priority notification. The effect of setting the same priorities may differ slightly on different platforms. Note this priority differs from `AndroidMessagePriority`. This priority is processed by the client after the message has been delivered, whereas [AndroidMessagePriority](https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#androidmessagepriority) is an FCM concept that controls when the message is delivered.
288 #[serde(rename = "notificationPriority")]
289 pub notification_priority: Option<String>,
290 /// Setting to control when a notification may be proxied.
291 pub proxy: Option<String>,
292 /// The sound to play when the device receives the notification. Supports "default" or the filename of a sound resource bundled in the app. Sound files must reside in /res/raw/.
293 pub sound: Option<String>,
294 /// When set to false or unset, the notification is automatically dismissed when the user clicks it in the panel. When set to true, the notification persists even when the user clicks it.
295 pub sticky: Option<bool>,
296 /// Identifier used to replace existing notifications in the notification drawer. If not specified, each request creates a new notification. If specified and a notification with the same tag is already being shown, the new notification replaces the existing one in the notification drawer.
297 pub tag: Option<String>,
298 /// Sets the "ticker" text, which is sent to accessibility services. Prior to API level 21 (`Lollipop`), sets the text that is displayed in the status bar when the notification first arrives.
299 pub ticker: Option<String>,
300 /// The notification's title. If present, it will override google.firebase.fcm.v1.Notification.title.
301 pub title: Option<String>,
302 /// Variable string values to be used in place of the format specifiers in title_loc_key to use to localize the title text to the user's current localization. See [Formatting and Styling](https://goo.gl/MalYE3) for more information.
303 #[serde(rename = "titleLocArgs")]
304 pub title_loc_args: Option<Vec<String>>,
305 /// The key to the title string in the app's string resources to use to localize the title text to the user's current localization. See [String Resources](https://goo.gl/NdFZGI) for more information.
306 #[serde(rename = "titleLocKey")]
307 pub title_loc_key: Option<String>,
308 /// Set the vibration pattern to use. Pass in an array of [protobuf.Duration](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Duration) to turn on or off the vibrator. The first value indicates the `Duration` to wait before turning the vibrator on. The next value indicates the `Duration` to keep the vibrator on. Subsequent values alternate between `Duration` to turn the vibrator off and to turn the vibrator on. If `vibrate_timings` is set and `default_vibrate_timings` is set to `true`, the default value is used instead of the user-specified `vibrate_timings`.
309 #[serde(rename = "vibrateTimings")]
310 #[serde_as(as = "Option<Vec<common::serde::duration::Wrapper>>")]
311 pub vibrate_timings: Option<Vec<chrono::Duration>>,
312 /// Set the [Notification.visibility](https://developer.android.com/reference/android/app/Notification.html#visibility) of the notification.
313 pub visibility: Option<String>,
314}
315
316impl common::Part for AndroidNotification {}
317
318/// [Apple Push Notification Service](https://goo.gl/MXRTPa) specific options.
319///
320/// This type is not used in any activity, and only used as *part* of another schema.
321///
322#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
323#[serde_with::serde_as]
324#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
325pub struct ApnsConfig {
326 /// Options for features provided by the FCM SDK for iOS.
327 #[serde(rename = "fcmOptions")]
328 pub fcm_options: Option<ApnsFcmOptions>,
329 /// HTTP request headers defined in Apple Push Notification Service. Refer to [APNs request headers](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns) for supported headers such as `apns-expiration` and `apns-priority`. The backend sets a default value for `apns-expiration` of 30 days and a default value for `apns-priority` of 10 if not explicitly set.
330 pub headers: Option<HashMap<String, String>>,
331 /// Optional. [Apple Live Activity](https://developer.apple.com/design/human-interface-guidelines/live-activities) token to send updates to. This token can either be a push token or [push-to-start](https://developer.apple.com/documentation/activitykit/activity/pushtostarttoken) token from Apple. To start, update, or end a live activity remotely using FCM, construct an [`aps payload`](https://developer.apple.com/documentation/activitykit/starting-and-updating-live-activities-with-activitykit-push-notifications#Construct-the-payload-that-starts-a-Live-Activity) and put it in the [`apns.payload`](https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#ApnsConfig) field.
332 #[serde(rename = "liveActivityToken")]
333 pub live_activity_token: Option<String>,
334 /// APNs payload as a JSON object, including both `aps` dictionary and custom payload. See [Payload Key Reference](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/generating_a_remote_notification). If present, it overrides google.firebase.fcm.v1.Notification.title and google.firebase.fcm.v1.Notification.body.
335 pub payload: Option<HashMap<String, serde_json::Value>>,
336}
337
338impl common::Part for ApnsConfig {}
339
340/// Options for features provided by the FCM SDK for iOS.
341///
342/// This type is not used in any activity, and only used as *part* of another schema.
343///
344#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
345#[serde_with::serde_as]
346#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
347pub struct ApnsFcmOptions {
348 /// Label associated with the message's analytics data.
349 #[serde(rename = "analyticsLabel")]
350 pub analytics_label: Option<String>,
351 /// Contains the URL of an image that is going to be displayed in a notification. If present, it will override google.firebase.fcm.v1.Notification.image.
352 pub image: Option<String>,
353}
354
355impl common::Part for ApnsFcmOptions {}
356
357/// Represents a color in the RGBA color space. This representation is designed for simplicity of conversion to and from color representations in various languages over compactness. For example, the fields of this representation can be trivially provided to the constructor of `java.awt.Color` in Java; it can also be trivially provided to UIColor's `+colorWithRed:green:blue:alpha` method in iOS; and, with just a little work, it can be easily formatted into a CSS `rgba()` string in JavaScript. This reference page doesn't have information about the absolute color space that should be used to interpret the RGB value—for example, sRGB, Adobe RGB, DCI-P3, and BT.2020. By default, applications should assume the sRGB color space. When color equality needs to be decided, implementations, unless documented otherwise, treat two colors as equal if all their red, green, blue, and alpha values each differ by at most `1e-5`. Example (Java): import com.google.type.Color; // ... public static java.awt.Color fromProto(Color protocolor) { float alpha = protocolor.hasAlpha() ? protocolor.getAlpha().getValue() : 1.0; return new java.awt.Color( protocolor.getRed(), protocolor.getGreen(), protocolor.getBlue(), alpha); } public static Color toProto(java.awt.Color color) { float red = (float) color.getRed(); float green = (float) color.getGreen(); float blue = (float) color.getBlue(); float denominator = 255.0; Color.Builder resultBuilder = Color .newBuilder() .setRed(red / denominator) .setGreen(green / denominator) .setBlue(blue / denominator); int alpha = color.getAlpha(); if (alpha != 255) { result.setAlpha( FloatValue .newBuilder() .setValue(((float) alpha) / denominator) .build()); } return resultBuilder.build(); } // ... Example (iOS / Obj-C): // ... static UIColor* fromProto(Color* protocolor) { float red = [protocolor red]; float green = [protocolor green]; float blue = [protocolor blue]; FloatValue* alpha_wrapper = [protocolor alpha]; float alpha = 1.0; if (alpha_wrapper != nil) { alpha = [alpha_wrapper value]; } return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; } static Color* toProto(UIColor* color) { CGFloat red, green, blue, alpha; if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) { return nil; } Color* result = [[Color alloc] init]; [result setRed:red]; [result setGreen:green]; [result setBlue:blue]; if (alpha <= 0.9999) { [result setAlpha:floatWrapperWithValue(alpha)]; } [result autorelease]; return result; } // ... Example (JavaScript): // ... var protoToCssColor = function(rgb_color) { var redFrac = rgb_color.red || 0.0; var greenFrac = rgb_color.green || 0.0; var blueFrac = rgb_color.blue || 0.0; var red = Math.floor(redFrac * 255); var green = Math.floor(greenFrac * 255); var blue = Math.floor(blueFrac * 255); if (!('alpha' in rgb_color)) { return rgbToCssColor(red, green, blue); } var alphaFrac = rgb_color.alpha.value || 0.0; var rgbParams = [red, green, blue].join(','); return ['rgba(', rgbParams, ',', alphaFrac, ')'].join(''); }; var rgbToCssColor = function(red, green, blue) { var rgbNumber = new Number((red << 16) | (green << 8) | blue); var hexString = rgbNumber.toString(16); var missingZeros = 6 - hexString.length; var resultBuilder = ['#']; for (var i = 0; i < missingZeros; i++) { resultBuilder.push('0'); } resultBuilder.push(hexString); return resultBuilder.join(''); }; // ...
358///
359/// This type is not used in any activity, and only used as *part* of another schema.
360///
361#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
362#[serde_with::serde_as]
363#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
364pub struct Color {
365 /// The fraction of this color that should be applied to the pixel. That is, the final pixel color is defined by the equation: `pixel color = alpha * (this color) + (1.0 - alpha) * (background color)` This means that a value of 1.0 corresponds to a solid color, whereas a value of 0.0 corresponds to a completely transparent color. This uses a wrapper message rather than a simple float scalar so that it is possible to distinguish between a default value and the value being unset. If omitted, this color object is rendered as a solid color (as if the alpha value had been explicitly given a value of 1.0).
366 pub alpha: Option<f32>,
367 /// The amount of blue in the color as a value in the interval [0, 1].
368 pub blue: Option<f32>,
369 /// The amount of green in the color as a value in the interval [0, 1].
370 pub green: Option<f32>,
371 /// The amount of red in the color as a value in the interval [0, 1].
372 pub red: Option<f32>,
373}
374
375impl common::Part for Color {}
376
377/// Platform independent options for features provided by the FCM SDKs.
378///
379/// This type is not used in any activity, and only used as *part* of another schema.
380///
381#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
382#[serde_with::serde_as]
383#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
384pub struct FcmOptions {
385 /// Label associated with the message's analytics data.
386 #[serde(rename = "analyticsLabel")]
387 pub analytics_label: Option<String>,
388}
389
390impl common::Part for FcmOptions {}
391
392/// Settings to control notification LED.
393///
394/// This type is not used in any activity, and only used as *part* of another schema.
395///
396#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
397#[serde_with::serde_as]
398#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
399pub struct LightSettings {
400 /// Required. Set `color` of the LED with [google.type.Color](https://github.com/googleapis/googleapis/blob/master/google/type/color.proto).
401 pub color: Option<Color>,
402 /// Required. Along with `light_on_duration `, define the blink rate of LED flashes. Resolution defined by [proto.Duration](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Duration)
403 #[serde(rename = "lightOffDuration")]
404 #[serde_as(as = "Option<common::serde::duration::Wrapper>")]
405 pub light_off_duration: Option<chrono::Duration>,
406 /// Required. Along with `light_off_duration`, define the blink rate of LED flashes. Resolution defined by [proto.Duration](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Duration)
407 #[serde(rename = "lightOnDuration")]
408 #[serde_as(as = "Option<common::serde::duration::Wrapper>")]
409 pub light_on_duration: Option<chrono::Duration>,
410}
411
412impl common::Part for LightSettings {}
413
414/// Message to send by Firebase Cloud Messaging Service.
415///
416/// # Activities
417///
418/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
419/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
420///
421/// * [messages send projects](ProjectMessageSendCall) (response)
422#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
423#[serde_with::serde_as]
424#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
425pub struct Message {
426 /// Input only. Android specific options for messages sent through [FCM connection server](https://goo.gl/4GLdUl).
427 pub android: Option<AndroidConfig>,
428 /// Input only. [Apple Push Notification Service](https://goo.gl/MXRTPa) specific options.
429 pub apns: Option<ApnsConfig>,
430 /// Condition to send a message to, e.g. "'foo' in topics && 'bar' in topics".
431 pub condition: Option<String>,
432 /// Input only. Arbitrary key/value payload, which must be UTF-8 encoded. The key should not be a reserved word (“from”, “message_type”, or any word starting with “google.” or “gcm.notification.”). When sending payloads containing only data fields to iOS devices, only normal priority (`"apns-priority": "5"`) is allowed in [`ApnsConfig`](https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#apnsconfig).
433 pub data: Option<HashMap<String, String>>,
434 /// Input only. Template for FCM SDK feature options to use across all platforms.
435 #[serde(rename = "fcmOptions")]
436 pub fcm_options: Option<FcmOptions>,
437 /// Output Only. The identifier of the message sent, in the format of `projects/*/messages/{message_id}`.
438 pub name: Option<String>,
439 /// Input only. Basic notification template to use across all platforms.
440 pub notification: Option<Notification>,
441 /// Registration token to send a message to.
442 pub token: Option<String>,
443 /// Topic name to send a message to, e.g. "weather". Note: "/topics/" prefix should not be provided.
444 pub topic: Option<String>,
445 /// Input only. [Webpush protocol](https://tools.ietf.org/html/rfc8030) options.
446 pub webpush: Option<WebpushConfig>,
447}
448
449impl common::ResponseResult for Message {}
450
451/// Basic notification template to use across all platforms.
452///
453/// This type is not used in any activity, and only used as *part* of another schema.
454///
455#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
456#[serde_with::serde_as]
457#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
458pub struct Notification {
459 /// The notification's body text.
460 pub body: Option<String>,
461 /// Contains the URL of an image that is going to be downloaded on the device and displayed in a notification. JPEG, PNG, BMP have full support across platforms. Animated GIF and video only work on iOS. WebP and HEIF have varying levels of support across platforms and platform versions. Android has 1MB image size limit. Quota usage and implications/costs for hosting image on Firebase Storage: https://firebase.google.com/pricing
462 pub image: Option<String>,
463 /// The notification's title.
464 pub title: Option<String>,
465}
466
467impl common::Part for Notification {}
468
469/// Request to send a message to specified target.
470///
471/// # Activities
472///
473/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
474/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
475///
476/// * [messages send projects](ProjectMessageSendCall) (request)
477#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
478#[serde_with::serde_as]
479#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
480pub struct SendMessageRequest {
481 /// Required. Message to send.
482 pub message: Option<Message>,
483 /// Flag for testing the request without actually delivering the message.
484 #[serde(rename = "validateOnly")]
485 pub validate_only: Option<bool>,
486}
487
488impl common::RequestValue for SendMessageRequest {}
489
490/// [Webpush protocol](https://tools.ietf.org/html/rfc8030) options.
491///
492/// This type is not used in any activity, and only used as *part* of another schema.
493///
494#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
495#[serde_with::serde_as]
496#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
497pub struct WebpushConfig {
498 /// Arbitrary key/value payload. If present, it will override google.firebase.fcm.v1.Message.data.
499 pub data: Option<HashMap<String, String>>,
500 /// Options for features provided by the FCM SDK for Web.
501 #[serde(rename = "fcmOptions")]
502 pub fcm_options: Option<WebpushFcmOptions>,
503 /// HTTP headers defined in webpush protocol. Refer to [Webpush protocol](https://tools.ietf.org/html/rfc8030#section-5) for supported headers, e.g. "TTL": "15".
504 pub headers: Option<HashMap<String, String>>,
505 /// Web Notification options as a JSON object. Supports Notification instance properties as defined in [Web Notification API](https://developer.mozilla.org/en-US/docs/Web/API/Notification). If present, "title" and "body" fields override [google.firebase.fcm.v1.Notification.title] and [google.firebase.fcm.v1.Notification.body].
506 pub notification: Option<HashMap<String, serde_json::Value>>,
507}
508
509impl common::Part for WebpushConfig {}
510
511/// Options for features provided by the FCM SDK for Web.
512///
513/// This type is not used in any activity, and only used as *part* of another schema.
514///
515#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
516#[serde_with::serde_as]
517#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
518pub struct WebpushFcmOptions {
519 /// Label associated with the message's analytics data.
520 #[serde(rename = "analyticsLabel")]
521 pub analytics_label: Option<String>,
522 /// The link to open when the user clicks on the notification. For all URL values, HTTPS is required.
523 pub link: Option<String>,
524}
525
526impl common::Part for WebpushFcmOptions {}
527
528// ###################
529// MethodBuilders ###
530// #################
531
532/// A builder providing access to all methods supported on *project* resources.
533/// It is not used directly, but through the [`FirebaseCloudMessaging`] hub.
534///
535/// # Example
536///
537/// Instantiate a resource builder
538///
539/// ```test_harness,no_run
540/// extern crate hyper;
541/// extern crate hyper_rustls;
542/// extern crate google_fcm1 as fcm1;
543///
544/// # async fn dox() {
545/// use fcm1::{FirebaseCloudMessaging, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
546///
547/// let secret: yup_oauth2::ApplicationSecret = Default::default();
548/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
549/// .with_native_roots()
550/// .unwrap()
551/// .https_only()
552/// .enable_http2()
553/// .build();
554///
555/// let executor = hyper_util::rt::TokioExecutor::new();
556/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
557/// secret,
558/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
559/// yup_oauth2::client::CustomHyperClientBuilder::from(
560/// hyper_util::client::legacy::Client::builder(executor).build(connector),
561/// ),
562/// ).build().await.unwrap();
563///
564/// let client = hyper_util::client::legacy::Client::builder(
565/// hyper_util::rt::TokioExecutor::new()
566/// )
567/// .build(
568/// hyper_rustls::HttpsConnectorBuilder::new()
569/// .with_native_roots()
570/// .unwrap()
571/// .https_or_http()
572/// .enable_http2()
573/// .build()
574/// );
575/// let mut hub = FirebaseCloudMessaging::new(client, auth);
576/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
577/// // like `messages_send(...)`
578/// // to build up your call.
579/// let rb = hub.projects();
580/// # }
581/// ```
582pub struct ProjectMethods<'a, C>
583where
584 C: 'a,
585{
586 hub: &'a FirebaseCloudMessaging<C>,
587}
588
589impl<'a, C> common::MethodsBuilder for ProjectMethods<'a, C> {}
590
591impl<'a, C> ProjectMethods<'a, C> {
592 /// Create a builder to help you perform the following task:
593 ///
594 /// Send a message to specified target (a registration token, topic or condition).
595 ///
596 /// # Arguments
597 ///
598 /// * `request` - No description provided.
599 /// * `parent` - Required. It contains the Firebase project id (i.e. the unique identifier for your Firebase project), in the format of `projects/{project_id}`. The numeric project number with no padding is also supported in the format of `projects/{project_number}`.
600 pub fn messages_send(
601 &self,
602 request: SendMessageRequest,
603 parent: &str,
604 ) -> ProjectMessageSendCall<'a, C> {
605 ProjectMessageSendCall {
606 hub: self.hub,
607 _request: request,
608 _parent: parent.to_string(),
609 _delegate: Default::default(),
610 _additional_params: Default::default(),
611 _scopes: Default::default(),
612 }
613 }
614}
615
616// ###################
617// CallBuilders ###
618// #################
619
620/// Send a message to specified target (a registration token, topic or condition).
621///
622/// A builder for the *messages.send* method supported by a *project* resource.
623/// It is not used directly, but through a [`ProjectMethods`] instance.
624///
625/// # Example
626///
627/// Instantiate a resource method builder
628///
629/// ```test_harness,no_run
630/// # extern crate hyper;
631/// # extern crate hyper_rustls;
632/// # extern crate google_fcm1 as fcm1;
633/// use fcm1::api::SendMessageRequest;
634/// # async fn dox() {
635/// # use fcm1::{FirebaseCloudMessaging, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
636///
637/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
638/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
639/// # .with_native_roots()
640/// # .unwrap()
641/// # .https_only()
642/// # .enable_http2()
643/// # .build();
644///
645/// # let executor = hyper_util::rt::TokioExecutor::new();
646/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
647/// # secret,
648/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
649/// # yup_oauth2::client::CustomHyperClientBuilder::from(
650/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
651/// # ),
652/// # ).build().await.unwrap();
653///
654/// # let client = hyper_util::client::legacy::Client::builder(
655/// # hyper_util::rt::TokioExecutor::new()
656/// # )
657/// # .build(
658/// # hyper_rustls::HttpsConnectorBuilder::new()
659/// # .with_native_roots()
660/// # .unwrap()
661/// # .https_or_http()
662/// # .enable_http2()
663/// # .build()
664/// # );
665/// # let mut hub = FirebaseCloudMessaging::new(client, auth);
666/// // As the method needs a request, you would usually fill it with the desired information
667/// // into the respective structure. Some of the parts shown here might not be applicable !
668/// // Values shown here are possibly random and not representative !
669/// let mut req = SendMessageRequest::default();
670///
671/// // You can configure optional parameters by calling the respective setters at will, and
672/// // execute the final call using `doit()`.
673/// // Values shown here are possibly random and not representative !
674/// let result = hub.projects().messages_send(req, "parent")
675/// .doit().await;
676/// # }
677/// ```
678pub struct ProjectMessageSendCall<'a, C>
679where
680 C: 'a,
681{
682 hub: &'a FirebaseCloudMessaging<C>,
683 _request: SendMessageRequest,
684 _parent: String,
685 _delegate: Option<&'a mut dyn common::Delegate>,
686 _additional_params: HashMap<String, String>,
687 _scopes: BTreeSet<String>,
688}
689
690impl<'a, C> common::CallBuilder for ProjectMessageSendCall<'a, C> {}
691
692impl<'a, C> ProjectMessageSendCall<'a, C>
693where
694 C: common::Connector,
695{
696 /// Perform the operation you have build so far.
697 pub async fn doit(mut self) -> common::Result<(common::Response, Message)> {
698 use std::borrow::Cow;
699 use std::io::{Read, Seek};
700
701 use common::{url::Params, ToParts};
702 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
703
704 let mut dd = common::DefaultDelegate;
705 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
706 dlg.begin(common::MethodInfo {
707 id: "fcm.projects.messages.send",
708 http_method: hyper::Method::POST,
709 });
710
711 for &field in ["alt", "parent"].iter() {
712 if self._additional_params.contains_key(field) {
713 dlg.finished(false);
714 return Err(common::Error::FieldClash(field));
715 }
716 }
717
718 let mut params = Params::with_capacity(4 + self._additional_params.len());
719 params.push("parent", self._parent);
720
721 params.extend(self._additional_params.iter());
722
723 params.push("alt", "json");
724 let mut url = self.hub._base_url.clone() + "v1/{+parent}/messages:send";
725 if self._scopes.is_empty() {
726 self._scopes
727 .insert(Scope::CloudPlatform.as_ref().to_string());
728 }
729
730 #[allow(clippy::single_element_loop)]
731 for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
732 url = params.uri_replacement(url, param_name, find_this, true);
733 }
734 {
735 let to_remove = ["parent"];
736 params.remove_params(&to_remove);
737 }
738
739 let url = params.parse_with_url(&url);
740
741 let mut json_mime_type = mime::APPLICATION_JSON;
742 let mut request_value_reader = {
743 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
744 common::remove_json_null_values(&mut value);
745 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
746 serde_json::to_writer(&mut dst, &value).unwrap();
747 dst
748 };
749 let request_size = request_value_reader
750 .seek(std::io::SeekFrom::End(0))
751 .unwrap();
752 request_value_reader
753 .seek(std::io::SeekFrom::Start(0))
754 .unwrap();
755
756 loop {
757 let token = match self
758 .hub
759 .auth
760 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
761 .await
762 {
763 Ok(token) => token,
764 Err(e) => match dlg.token(e) {
765 Ok(token) => token,
766 Err(e) => {
767 dlg.finished(false);
768 return Err(common::Error::MissingToken(e));
769 }
770 },
771 };
772 request_value_reader
773 .seek(std::io::SeekFrom::Start(0))
774 .unwrap();
775 let mut req_result = {
776 let client = &self.hub.client;
777 dlg.pre_request();
778 let mut req_builder = hyper::Request::builder()
779 .method(hyper::Method::POST)
780 .uri(url.as_str())
781 .header(USER_AGENT, self.hub._user_agent.clone());
782
783 if let Some(token) = token.as_ref() {
784 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
785 }
786
787 let request = req_builder
788 .header(CONTENT_TYPE, json_mime_type.to_string())
789 .header(CONTENT_LENGTH, request_size as u64)
790 .body(common::to_body(
791 request_value_reader.get_ref().clone().into(),
792 ));
793
794 client.request(request.unwrap()).await
795 };
796
797 match req_result {
798 Err(err) => {
799 if let common::Retry::After(d) = dlg.http_error(&err) {
800 sleep(d).await;
801 continue;
802 }
803 dlg.finished(false);
804 return Err(common::Error::HttpError(err));
805 }
806 Ok(res) => {
807 let (mut parts, body) = res.into_parts();
808 let mut body = common::Body::new(body);
809 if !parts.status.is_success() {
810 let bytes = common::to_bytes(body).await.unwrap_or_default();
811 let error = serde_json::from_str(&common::to_string(&bytes));
812 let response = common::to_response(parts, bytes.into());
813
814 if let common::Retry::After(d) =
815 dlg.http_failure(&response, error.as_ref().ok())
816 {
817 sleep(d).await;
818 continue;
819 }
820
821 dlg.finished(false);
822
823 return Err(match error {
824 Ok(value) => common::Error::BadRequest(value),
825 _ => common::Error::Failure(response),
826 });
827 }
828 let response = {
829 let bytes = common::to_bytes(body).await.unwrap_or_default();
830 let encoded = common::to_string(&bytes);
831 match serde_json::from_str(&encoded) {
832 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
833 Err(error) => {
834 dlg.response_json_decode_error(&encoded, &error);
835 return Err(common::Error::JsonDecodeError(
836 encoded.to_string(),
837 error,
838 ));
839 }
840 }
841 };
842
843 dlg.finished(true);
844 return Ok(response);
845 }
846 }
847 }
848 }
849
850 ///
851 /// Sets the *request* property to the given value.
852 ///
853 /// Even though the property as already been set when instantiating this call,
854 /// we provide this method for API completeness.
855 pub fn request(mut self, new_value: SendMessageRequest) -> ProjectMessageSendCall<'a, C> {
856 self._request = new_value;
857 self
858 }
859 /// Required. It contains the Firebase project id (i.e. the unique identifier for your Firebase project), in the format of `projects/{project_id}`. The numeric project number with no padding is also supported in the format of `projects/{project_number}`.
860 ///
861 /// Sets the *parent* path property to the given value.
862 ///
863 /// Even though the property as already been set when instantiating this call,
864 /// we provide this method for API completeness.
865 pub fn parent(mut self, new_value: &str) -> ProjectMessageSendCall<'a, C> {
866 self._parent = new_value.to_string();
867 self
868 }
869 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
870 /// while executing the actual API request.
871 ///
872 /// ````text
873 /// It should be used to handle progress information, and to implement a certain level of resilience.
874 /// ````
875 ///
876 /// Sets the *delegate* property to the given value.
877 pub fn delegate(
878 mut self,
879 new_value: &'a mut dyn common::Delegate,
880 ) -> ProjectMessageSendCall<'a, C> {
881 self._delegate = Some(new_value);
882 self
883 }
884
885 /// Set any additional parameter of the query string used in the request.
886 /// It should be used to set parameters which are not yet available through their own
887 /// setters.
888 ///
889 /// Please note that this method must not be used to set any of the known parameters
890 /// which have their own setter method. If done anyway, the request will fail.
891 ///
892 /// # Additional Parameters
893 ///
894 /// * *$.xgafv* (query-string) - V1 error format.
895 /// * *access_token* (query-string) - OAuth access token.
896 /// * *alt* (query-string) - Data format for response.
897 /// * *callback* (query-string) - JSONP
898 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
899 /// * *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.
900 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
901 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
902 /// * *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.
903 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
904 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
905 pub fn param<T>(mut self, name: T, value: T) -> ProjectMessageSendCall<'a, C>
906 where
907 T: AsRef<str>,
908 {
909 self._additional_params
910 .insert(name.as_ref().to_string(), value.as_ref().to_string());
911 self
912 }
913
914 /// Identifies the authorization scope for the method you are building.
915 ///
916 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
917 /// [`Scope::CloudPlatform`].
918 ///
919 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
920 /// tokens for more than one scope.
921 ///
922 /// Usually there is more than one suitable scope to authorize an operation, some of which may
923 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
924 /// sufficient, a read-write scope will do as well.
925 pub fn add_scope<St>(mut self, scope: St) -> ProjectMessageSendCall<'a, C>
926 where
927 St: AsRef<str>,
928 {
929 self._scopes.insert(String::from(scope.as_ref()));
930 self
931 }
932 /// Identifies the authorization scope(s) for the method you are building.
933 ///
934 /// See [`Self::add_scope()`] for details.
935 pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectMessageSendCall<'a, C>
936 where
937 I: IntoIterator<Item = St>,
938 St: AsRef<str>,
939 {
940 self._scopes
941 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
942 self
943 }
944
945 /// Removes all scopes, and no default scope will be used either.
946 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
947 /// for details).
948 pub fn clear_scopes(mut self) -> ProjectMessageSendCall<'a, C> {
949 self._scopes.clear();
950 self
951 }
952}