hi_push/fcm/model.rs
1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use std::default::Default;
4
5
6
7/// Identifies the an OAuth2 authorization scope.
8/// A scope is needed when requesting an
9/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
10#[derive(PartialEq, Eq, Hash)]
11pub enum Scope {
12 /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
13 CloudPlatform,
14
15 /// Send messages and manage messaging subscriptions for your Firebase applications
16 FirebaseMessaging,
17}
18
19impl AsRef<str> for Scope {
20 fn as_ref(&self) -> &str {
21 match *self {
22 Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
23 Scope::FirebaseMessaging => "https://www.googleapis.com/auth/firebase.messaging",
24 }
25 }
26}
27
28impl Default for Scope {
29 fn default() -> Scope {
30 Scope::CloudPlatform
31 }
32}
33
34
35/// Android specific options for messages sent through [FCM connection server](https://goo.gl/4GLdUl).
36///
37/// This type is not used in any activity, and only used as *part* of another schema.
38///
39#[derive(Default, Clone, Debug, Serialize, Deserialize)]
40pub struct AndroidConfig {
41 /// 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.
42 #[serde(rename = "collapseKey")]
43 pub collapse_key: Option<String>,
44 /// Arbitrary key/value payload. If present, it will override google.firebase.fcm.v1.Message.data.
45 pub data: Option<HashMap<String, String>>,
46 /// 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).
47 #[serde(rename = "directBootOk")]
48 pub direct_boot_ok: Option<bool>,
49 /// Options for features provided by the FCM SDK for Android.
50 #[serde(rename = "fcmOptions")]
51 pub fcm_options: Option<AndroidFcmOptions>,
52 /// Notification to send to android devices.
53 pub notification: Option<AndroidNotification>,
54 /// Message priority. Can take "normal" and "high" values. For more information, see [Setting the priority of a message](https://goo.gl/GjONJv).
55 pub priority: Option<String>,
56 /// Package name of the application where the registration token must match in order to receive the message.
57 #[serde(rename = "restrictedPackageName")]
58 pub restricted_package_name: Option<String>,
59 /// 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.
60 pub ttl: Option<String>,
61}
62
63/// Options for features provided by the FCM SDK for Android.
64///
65/// This type is not used in any activity, and only used as *part* of another schema.
66///
67#[derive(Default, Clone, Debug, Serialize, Deserialize)]
68pub struct AndroidFcmOptions {
69 /// Label associated with the message's analytics data.
70 #[serde(rename = "analyticsLabel")]
71 pub analytics_label: Option<String>,
72}
73
74
75/// Notification to send to android devices.
76///
77/// This type is not used in any activity, and only used as *part* of another schema.
78///
79#[derive(Default, Clone, Debug, Serialize, Deserialize)]
80pub struct AndroidNotification {
81 /// The notification's body text. If present, it will override google.firebase.fcm.v1.Notification.body.
82 pub body: Option<String>,
83 /// 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.
84 #[serde(rename = "bodyLocArgs")]
85 pub body_loc_args: Option<Vec<String>>,
86 /// 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.
87 #[serde(rename = "bodyLocKey")]
88 pub body_loc_key: Option<String>,
89 /// 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.
90 #[serde(rename = "channelId")]
91 pub channel_id: Option<String>,
92 /// 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.
93 #[serde(rename = "clickAction")]
94 pub click_action: Option<String>,
95 /// The notification's icon color, expressed in #rrggbb format.
96 pub color: Option<String>,
97 /// 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.
98 #[serde(rename = "defaultLightSettings")]
99 pub default_light_settings: Option<bool>,
100 /// 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).
101 #[serde(rename = "defaultSound")]
102 pub default_sound: Option<bool>,
103 /// 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`.
104 #[serde(rename = "defaultVibrateTimings")]
105 pub default_vibrate_timings: Option<bool>,
106 /// 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).
107 #[serde(rename = "eventTime")]
108 pub event_time: Option<String>,
109 /// 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.
110 pub icon: Option<String>,
111 /// 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.
112 pub image: Option<String>,
113 /// 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.
114 #[serde(rename = "lightSettings")]
115 pub light_settings: Option<LightSettings>,
116 /// 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)
117 #[serde(rename = "localOnly")]
118 pub local_only: Option<bool>,
119 /// 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.
120 #[serde(rename = "notificationCount")]
121 pub notification_count: Option<i32>,
122 /// 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.
123 #[serde(rename = "notificationPriority")]
124 pub notification_priority: Option<String>,
125 /// 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/.
126 pub sound: Option<String>,
127 /// 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.
128 pub sticky: Option<bool>,
129 /// 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.
130 pub tag: Option<String>,
131 /// 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.
132 pub ticker: Option<String>,
133 /// The notification's title. If present, it will override google.firebase.fcm.v1.Notification.title.
134 pub title: Option<String>,
135 /// 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.
136 #[serde(rename = "titleLocArgs")]
137 pub title_loc_args: Option<Vec<String>>,
138 /// 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.
139 #[serde(rename = "titleLocKey")]
140 pub title_loc_key: Option<String>,
141 /// 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`.
142 #[serde(rename = "vibrateTimings")]
143 pub vibrate_timings: Option<Vec<String>>,
144 /// Set the [Notification.visibility](https://developer.android.com/reference/android/app/Notification.html#visibility) of the notification.
145 pub visibility: Option<String>,
146}
147
148
149/// [Apple Push Notification Service](https://goo.gl/MXRTPa) specific options.
150///
151/// This type is not used in any activity, and only used as *part* of another schema.
152///
153#[derive(Default, Clone, Debug, Serialize, Deserialize)]
154pub struct ApnsConfig {
155 /// Options for features provided by the FCM SDK for iOS.
156 #[serde(rename = "fcmOptions")]
157 pub fcm_options: Option<ApnsFcmOptions>,
158 /// 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`.
159 pub headers: Option<HashMap<String, String>>,
160 /// 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. 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.
161 pub payload: Option<HashMap<String, String>>,
162}
163
164
165/// Options for features provided by the FCM SDK for iOS.
166///
167/// This type is not used in any activity, and only used as *part* of another schema.
168///
169#[derive(Default, Clone, Debug, Serialize, Deserialize)]
170pub struct ApnsFcmOptions {
171 /// Label associated with the message's analytics data.
172 #[serde(rename = "analyticsLabel")]
173 pub analytics_label: Option<String>,
174 /// 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.
175 pub image: Option<String>,
176}
177
178
179/// Represents a color in the RGBA color space. This representation is designed for simplicity of conversion to/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 carry information about the absolute color space that should be used to interpret the RGB value (e.g. sRGB, Adobe RGB, DCI-P3, BT.2020, etc.). 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(''); }; // ...
180///
181/// This type is not used in any activity, and only used as *part* of another schema.
182///
183#[derive(Default, Clone, Debug, Serialize, Deserialize)]
184pub struct Color {
185 /// 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).
186 pub alpha: Option<f32>,
187 /// The amount of blue in the color as a value in the interval [0, 1].
188 pub blue: Option<f32>,
189 /// The amount of green in the color as a value in the interval [0, 1].
190 pub green: Option<f32>,
191 /// The amount of red in the color as a value in the interval [0, 1].
192 pub red: Option<f32>,
193}
194
195
196/// Platform independent options for features provided by the FCM SDKs.
197///
198/// This type is not used in any activity, and only used as *part* of another schema.
199///
200#[derive(Default, Clone, Debug, Serialize, Deserialize)]
201pub struct FcmOptions {
202 /// Label associated with the message's analytics data.
203 #[serde(rename = "analyticsLabel")]
204 pub analytics_label: Option<String>,
205}
206
207
208/// Settings to control notification LED.
209///
210/// This type is not used in any activity, and only used as *part* of another schema.
211///
212#[derive(Default, Clone, Debug, Serialize, Deserialize)]
213pub struct LightSettings {
214 /// Required. Set `color` of the LED with [google.type.Color](https://github.com/googleapis/googleapis/blob/master/google/type/color.proto).
215 pub color: Option<Color>,
216 /// 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)
217 #[serde(rename = "lightOffDuration")]
218 pub light_off_duration: Option<String>,
219 /// 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)
220 #[serde(rename = "lightOnDuration")]
221 pub light_on_duration: Option<String>,
222}
223
224
225/// Message to send by Firebase Cloud Messaging Service.
226///
227/// # Activities
228///
229/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
230/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
231///
232/// * [messages send projects](ProjectMessageSendCall) (response)
233///
234#[derive(Default, Clone, Debug, Serialize, Deserialize)]
235pub struct Message {
236 /// Input only. Android specific options for messages sent through [FCM connection server](https://goo.gl/4GLdUl).
237 pub android: Option<AndroidConfig>,
238 /// Input only. [Apple Push Notification Service](https://goo.gl/MXRTPa) specific options.
239 pub apns: Option<ApnsConfig>,
240 /// Condition to send a message to, e.g. "'foo' in topics && 'bar' in topics".
241 pub condition: Option<String>,
242 /// 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"). When sending payloads containing only data fields to iOS devices, only normal priority (`"apns-priority": "5"`) is allowed in [`ApnsConfig`](/docs/reference/fcm/rest/v1/projects.messages#apnsconfig).
243 pub data: Option<HashMap<String, String>>,
244 /// Input only. Template for FCM SDK feature options to use across all platforms.
245 #[serde(rename = "fcmOptions")]
246 pub fcm_options: Option<FcmOptions>,
247 /// Output Only. The identifier of the message sent, in the format of `projects/*/messages/{message_id}`.
248 pub name: Option<String>,
249 /// Input only. Basic notification template to use across all platforms.
250 pub notification: Option<Notification>,
251 /// Registration token to send a message to.
252 pub token: Option<String>,
253 /// Topic name to send a message to, e.g. "weather". Note: "/topics/" prefix should not be provided.
254 pub topic: Option<String>,
255 /// Input only. [Webpush protocol](https://tools.ietf.org/html/rfc8030) options.
256 pub webpush: Option<WebpushConfig>,
257}
258
259
260
261#[derive(Default, Clone, Debug, Serialize)]
262pub struct MulticastMessage<'a> {
263 pub tokens: Vec<&'a str>,
264 pub data: Option<HashMap<String, String>>,
265 pub notification: Option<Notification>,
266 pub android: Option<AndroidConfig>,
267 pub webpush: Option<WebpushConfig>,
268 pub apns: Option<ApnsConfig>,
269}
270
271impl MulticastMessage<'_> {
272 pub(crate) fn to_messages(&self) -> Vec<Message> {
273 let mut msgs = Vec::new();
274
275 for token in &self.tokens {
276 msgs.push(Message {
277 android: self.android.clone(),
278 apns: self.apns.clone(),
279 condition: None,
280 data: self.data.clone(),
281 fcm_options: None,
282 name: None,
283 notification: self.notification.clone(),
284 token: Some(token.to_string()),
285 topic: None,
286 webpush: self.webpush.clone(),
287 });
288 }
289 msgs
290 }
291}
292
293
294/// Basic notification template to use across all platforms.
295///
296/// This type is not used in any activity, and only used as *part* of another schema.
297///
298#[derive(Default, Clone, Debug, Serialize, Deserialize)]
299pub struct Notification {
300 /// The notification's body text.
301 pub body: Option<String>,
302 /// 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
303 pub image: Option<String>,
304 /// The notification's title.
305 pub title: Option<String>,
306}
307
308
309/// Request to send a message to specified target.
310///
311/// # Activities
312///
313/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
314/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
315///
316/// * [messages send projects](ProjectMessageSendCall) (request)
317///
318#[derive(Default, Clone, Debug, Serialize, Deserialize)]
319pub struct SendMessageRequest {
320 /// Required. Message to send.
321 pub message: Option<Message>,
322 /// Flag for testing the request without actually delivering the message.
323 #[serde(rename = "validateOnly")]
324 pub validate_only: Option<bool>,
325}
326
327
328/// [Webpush protocol](https://tools.ietf.org/html/rfc8030) options.
329///
330/// This type is not used in any activity, and only used as *part* of another schema.
331///
332#[derive(Default, Clone, Debug, Serialize, Deserialize)]
333pub struct WebpushConfig {
334 /// Arbitrary key/value payload. If present, it will override google.firebase.fcm.v1.Message.data.
335 pub data: Option<HashMap<String, String>>,
336 /// Options for features provided by the FCM SDK for Web.
337 #[serde(rename = "fcmOptions")]
338 pub fcm_options: Option<WebpushFcmOptions>,
339 /// 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".
340 pub headers: Option<HashMap<String, String>>,
341 /// 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].
342 pub notification: Option<HashMap<String, String>>,
343}
344
345
346/// Options for features provided by the FCM SDK for Web.
347///
348/// This type is not used in any activity, and only used as *part* of another schema.
349///
350#[derive(Default, Clone, Debug, Serialize, Deserialize)]
351pub struct WebpushFcmOptions {
352 /// Label associated with the message's analytics data.
353 #[serde(rename = "analyticsLabel")]
354 pub analytics_label: Option<String>,
355 /// The link to open when the user clicks on the notification. For all URL values, HTTPS is required.
356 pub link: Option<String>,
357}