From 2e7302ffcfd4742ee599b66e2e674c4d4d1475e6 Mon Sep 17 00:00:00 2001 From: Nick Williams Date: Sun, 29 Nov 2026 07:35:54 +0000 Subject: [PATCH] Add no-op Analytics, unsupported Cloud Messaging and in-memory Performance Monitoring for the JVM The Firebase Kotlin SDK has so far filled the gap of the three Firebase products this SDK did not port with JVM-only code of its own. This moves that code here, so that firebase-kotlin-sdk can treat Analytics, Cloud Messaging and Performance Monitoring like every other module on the JVM: its com.google.firebase sources become header stubs that are compiled against this jar, verified against it member by member and stripped. com.google.firebase.analytics is a no-op, as Google Analytics has no client for the JVM: FirebaseAnalytics accepts and drops events, user properties, the user ID and consent, and its instance and session IDs are null. It comes with the Event, Param and UserProperty constants, the ConsentType and ConsentStatus enums and the AnalyticsKt facade (Firebase.analytics, logEvent { } with ParametersBuilder, setConsent { } with ConsentBuilder) of the Android SDK. com.google.firebase.messaging has the FirebaseMessaging singleton and the MessagingKt facade, but messages are received through a device registration the JVM does not have, so every operation but isAutoInitEnabled throws an UnsupportedOperationException saying so. RemoteMessage, its Builder and Notification are an in-memory data holder backed by a Bundle and read through the keys the Android SDK uses, SendException carries its error codes and FirebaseMessagingService is a Service subclass whose callbacks are never invoked. com.google.firebase.perf keeps traces and HTTP metrics in memory: Trace records its metrics (while running, and atomically) and attributes, HttpMetric its response code, payload sizes, content type and attributes, and nothing is reported. FirebasePerformance is a process singleton that FirebasePerfRegistrar also registers as a Firebase component, so FirebaseApp.get(FirebasePerformance.class) works as on Android, and the PerformanceKt facade (Firebase.performance, trace { }) is included. Trace and RemoteMessage are Parcelable like the Android classes. For the Analytics items array, android.os.Bundle becomes Parcelable and stores parcelables and parcelable arrays, which android.os.Parcel now writes and reads as values. Application.getProcessName() is added, as firebase-common calls it when it reports that no default app is initialized. The version becomes 0.8.3. --- README.md | 10 + gradle.properties | 2 +- src/main/java/android/app/Application.kt | 7 + .../android/content/pm/PackageManager.java | 1 + src/main/java/android/os/Bundle.java | 50 +++- src/main/java/android/os/Parcel.java | 32 +++ .../google/firebase/analytics/Analytics.kt | 66 +++++ .../firebase/analytics/FirebaseAnalytics.kt | 212 +++++++++++++++ .../firebase/messaging/FirebaseMessaging.kt | 75 ++++++ .../messaging/FirebaseMessagingService.kt | 45 ++++ .../google/firebase/messaging/Messaging.kt | 14 + .../firebase/messaging/RemoteMessage.kt | 223 ++++++++++++++++ .../firebase/messaging/SendException.kt | 21 ++ .../firebase/perf/FirebasePerfRegistrar.java | 27 ++ .../firebase/perf/FirebasePerformance.kt | 63 +++++ .../com/google/firebase/perf/Performance.kt | 36 +++ .../google/firebase/perf/metrics/AddTrace.kt | 9 + .../firebase/perf/metrics/HttpMetric.kt | 117 +++++++++ .../com/google/firebase/perf/metrics/Trace.kt | 117 +++++++++ src/test/kotlin/BundleTest.kt | 36 +++ src/test/kotlin/FirebaseAnalyticsTest.kt | 122 +++++++++ src/test/kotlin/FirebaseMessagingTest.kt | 242 ++++++++++++++++++ src/test/kotlin/FirebasePerformanceTest.kt | 186 ++++++++++++++ src/test/kotlin/ParcelTest.kt | 13 + 24 files changed, 1721 insertions(+), 5 deletions(-) create mode 100644 src/main/java/com/google/firebase/analytics/Analytics.kt create mode 100644 src/main/java/com/google/firebase/analytics/FirebaseAnalytics.kt create mode 100644 src/main/java/com/google/firebase/messaging/FirebaseMessaging.kt create mode 100644 src/main/java/com/google/firebase/messaging/FirebaseMessagingService.kt create mode 100644 src/main/java/com/google/firebase/messaging/Messaging.kt create mode 100644 src/main/java/com/google/firebase/messaging/RemoteMessage.kt create mode 100644 src/main/java/com/google/firebase/messaging/SendException.kt create mode 100644 src/main/java/com/google/firebase/perf/FirebasePerfRegistrar.java create mode 100644 src/main/java/com/google/firebase/perf/FirebasePerformance.kt create mode 100644 src/main/java/com/google/firebase/perf/Performance.kt create mode 100644 src/main/java/com/google/firebase/perf/metrics/AddTrace.kt create mode 100644 src/main/java/com/google/firebase/perf/metrics/HttpMetric.kt create mode 100644 src/main/java/com/google/firebase/perf/metrics/Trace.kt create mode 100644 src/test/kotlin/FirebaseAnalyticsTest.kt create mode 100644 src/test/kotlin/FirebaseMessagingTest.kt create mode 100644 src/test/kotlin/FirebasePerformanceTest.kt diff --git a/README.md b/README.md index 1a83461..2e2d21d 100644 --- a/README.md +++ b/README.md @@ -130,9 +130,19 @@ The following libraries are available for the various Firebase products. | [Cloud Functions](https://firebase.google.com/docs/functions) | `22.1.1` | | [Remote Config](https://firebase.google.com/docs/remote-config) | `23.1.0`[^2] | | [Installations](https://firebase.google.com/docs/projects/manage-installations) | `19.1.2` | +| [Google Analytics](https://firebase.google.com/docs/analytics) | N/A[^3] | +| [Cloud Messaging](https://firebase.google.com/docs/cloud-messaging) | N/A[^4] | +| [Performance Monitoring](https://firebase.google.com/docs/perf-mon) | N/A[^5] | [^1]: Google has not open-sourced the Firebase Auth implementation for Android so a basic implementation using the Rest API is provided. [^2]: Realtime updates (`addOnConfigUpdateListener`) and defaults from XML resources are not supported. +[^3]: Google Analytics has no client for the JVM, so the `com.google.firebase.analytics` API is a no-op: events, user +properties and consent are accepted and dropped, the instance and session IDs are null. +[^4]: Messages are received through a device registration the JVM does not have, so `FirebaseMessaging.getInstance()` +exists but its operations throw `UnsupportedOperationException`; `RemoteMessage` and its `Builder` are an in-memory +data holder. +[^5]: There is no Performance Monitoring client for the JVM, so traces and HTTP metrics are kept in memory: they record +their metrics and attributes, which can be read back, and report nothing. Is the Firebase library or API you need missing? [Create an issue](https://github.com/GitLiveApp/firebase-java-sdk/issues/new?labels=API+coverage&template=increase-api-coverage.md&title=Add+%5Bclass+name%5D.%5Bfunction+name%5D+to+%5Blibrary+name) to request additional API coverage or be awesome and [submit a PR](https://github.com/GitLiveApp/firebase-java-sdk/fork). diff --git a/gradle.properties b/gradle.properties index ae8417c..19d3efe 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1 @@ -version=0.8.2 +version=0.8.3 diff --git a/src/main/java/android/app/Application.kt b/src/main/java/android/app/Application.kt index 672b85c..a015758 100644 --- a/src/main/java/android/app/Application.kt +++ b/src/main/java/android/app/Application.kt @@ -2,6 +2,7 @@ package android.app import android.content.ComponentCallbacks import android.content.Context +import java.io.File class Application : Context() { var minSdkVersion: Int = 0 @@ -14,4 +15,10 @@ class Application : Context() { } interface ActivityLifecycleCallbacks + + companion object { + /** The name of this process, which Firebase puts in the message of the error for a missing default app: the JVM's executable. */ + @JvmStatic + fun getProcessName(): String = ProcessHandle.current().info().command().map { File(it).name }.orElse("java") + } } diff --git a/src/main/java/android/content/pm/PackageManager.java b/src/main/java/android/content/pm/PackageManager.java index 7417b61..6212a8d 100644 --- a/src/main/java/android/content/pm/PackageManager.java +++ b/src/main/java/android/content/pm/PackageManager.java @@ -42,6 +42,7 @@ public ServiceInfo getServiceInfo(ComponentName component, int flags) throws Nam data.put("com.google.firebase.components:com.google.firebase.storage.StorageRegistrar", "com.google.firebase.components.ComponentRegistrar"); data.put("com.google.firebase.components:com.google.firebase.remoteconfig.RemoteConfigRegistrar", "com.google.firebase.components.ComponentRegistrar"); data.put("com.google.firebase.components:com.google.firebase.abt.component.AbtRegistrar", "com.google.firebase.components.ComponentRegistrar"); + data.put("com.google.firebase.components:com.google.firebase.perf.FirebasePerfRegistrar", "com.google.firebase.components.ComponentRegistrar"); return new ServiceInfo(data); } throw new IllegalArgumentException(component.cls); diff --git a/src/main/java/android/os/Bundle.java b/src/main/java/android/os/Bundle.java index 406ae48..ab3344b 100644 --- a/src/main/java/android/os/Bundle.java +++ b/src/main/java/android/os/Bundle.java @@ -6,11 +6,24 @@ import java.util.Set; /** - * A mapping from String keys to values, with the Android class's semantics for the primitive, String and Bundle values - * the ported Firebase libraries use: a getter returns its default when the key is missing or the value has another - * type, {@link #containsKey} answers rather than throws, and keys may be null. + * A mapping from String keys to values, with the Android class's semantics for the primitive, String, Bundle and + * Parcelable values the ported Firebase libraries use: a getter returns its default when the key is missing or the + * value has another type, {@link #containsKey} answers rather than throws, and keys may be null. Like Android's it is + * itself a {@link Parcelable}, written as its entries. */ -public class Bundle { +public class Bundle implements Parcelable { + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + @Override + public Bundle createFromParcel(Parcel source) { + return source.readBundle(); + } + + @Override + public Bundle[] newArray(int size) { + return new Bundle[size]; + } + }; private final Map data; @@ -87,6 +100,15 @@ public void putBundle(String key, Bundle value) { data.put(key, value); } + public void putParcelable(String key, Parcelable value) { + data.put(key, value); + } + + /** Stores an array of parcelables, such as the {@code items} of an Analytics e-commerce event. */ + public void putParcelableArray(String key, Parcelable[] value) { + data.put(key, value); + } + public boolean getBoolean(String key) { return getBoolean(key, false); } @@ -141,6 +163,26 @@ public Bundle getBundle(String key) { return get(key, Bundle.class, null); } + @SuppressWarnings("unchecked") + public T getParcelable(String key) { + return (T) get(key, Parcelable.class, null); + } + + public Parcelable[] getParcelableArray(String key) { + return get(key, Parcelable[].class, null); + } + + @Override + public int describeContents() { + return 0; + } + + /** Writes the entries with {@link Parcel#writeBundle}; {@link #CREATOR} reads them back with {@link Parcel#readBundle()}. */ + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeBundle(this); + } + private T get(String key, Class type, T defaultValue) { Object value = data.get(key); return type.isInstance(value) ? type.cast(value) : defaultValue; diff --git a/src/main/java/android/os/Parcel.java b/src/main/java/android/os/Parcel.java index 4225b1b..eca3005 100644 --- a/src/main/java/android/os/Parcel.java +++ b/src/main/java/android/os/Parcel.java @@ -49,6 +49,7 @@ public final class Parcel { private static final int VAL_LIST = 11; private static final int VAL_BYTEARRAY = 13; private static final int VAL_STRINGARRAY = 14; + private static final int VAL_PARCELABLEARRAY = 16; private static final int VAL_BYTE = 20; private static final int VAL_SERIALIZABLE = 21; @@ -350,6 +351,18 @@ public void writeParcelable(@Nullable Parcelable p, int parcelableFlags) { p.writeToParcel(this, parcelableFlags); } + /** Writes the length of the array, or -1 for a null array, followed by each element with {@link #writeParcelable}. */ + public void writeParcelableArray(@Nullable T[] value, int parcelableFlags) { + if (value == null) { + writeInt(-1); + return; + } + writeInt(value.length); + for (T element : value) { + writeParcelable(element, parcelableFlags); + } + } + /** * Writes a serialized snapshot of the object, so that changing it afterwards does not change the parcel and each * {@link #readSerializable()} returns a fresh copy. @@ -405,6 +418,9 @@ public void writeValue(@Nullable Object v) { } else if (v instanceof String[]) { writeInt(VAL_STRINGARRAY); writeStringList(Arrays.asList((String[]) v)); + } else if (v instanceof Parcelable[]) { + writeInt(VAL_PARCELABLEARRAY); + writeParcelableArray((Parcelable[]) v, 0); } else if (v instanceof Byte) { writeInt(VAL_BYTE); writeByte((Byte) v); @@ -628,6 +644,20 @@ public T readParcelable(@Nullable ClassLoader loader) { return (T) creator.createFromParcel(this); } + /** Reads the array {@link #writeParcelableArray} wrote, each element through its class's {@code CREATOR}. */ + @Nullable + public Parcelable[] readParcelableArray(@Nullable ClassLoader loader) { + int n = readInt(); + if (n < 0) { + return null; + } + Parcelable[] result = new Parcelable[n]; + for (int i = 0; i < n; i++) { + result[i] = readParcelable(loader); + } + return result; + } + /** * Deserializes a fresh copy of the object {@link #writeSerializable} wrote. This is the only place the parcel * deserializes anything: {@link #unmarshall} keeps serialized objects as bytes until a caller asks for them here. @@ -672,6 +702,8 @@ public Object readValue(@Nullable ClassLoader loader) { case VAL_STRINGARRAY: ArrayList strings = createStringArrayList(); return strings == null ? null : strings.toArray(new String[0]); + case VAL_PARCELABLEARRAY: + return readParcelableArray(loader); case VAL_BYTE: return readByte(); case VAL_SERIALIZABLE: diff --git a/src/main/java/com/google/firebase/analytics/Analytics.kt b/src/main/java/com/google/firebase/analytics/Analytics.kt new file mode 100644 index 0000000..eb10fcf --- /dev/null +++ b/src/main/java/com/google/firebase/analytics/Analytics.kt @@ -0,0 +1,66 @@ +/* + * The Kotlin extensions the Android SDK's firebase-analytics ships as com.google.firebase.analytics.AnalyticsKt, with + * their ParametersBuilder and ConsentBuilder, so that code written against them compiles against this SDK like it does + * against the other ported libraries' facades. + */ +package com.google.firebase.analytics + +import android.os.Bundle +import com.google.firebase.Firebase + +/** Returns the [FirebaseAnalytics] instance of the default app. */ +val Firebase.analytics: FirebaseAnalytics + get() = FirebaseAnalytics.getInstance(com.google.firebase.FirebaseApp.getInstance().applicationContext) + +/** Logs an event with the parameters set by [block], e.g. `logEvent(FirebaseAnalytics.Event.LOGIN) { param(FirebaseAnalytics.Param.METHOD, "email") }`. */ +inline fun FirebaseAnalytics.logEvent(name: String, block: ParametersBuilder.() -> Unit) { + logEvent(name, ParametersBuilder().apply(block).bundle) +} + +/** Sets the consent settings assigned by [block], e.g. `setConsent { adStorage = FirebaseAnalytics.ConsentStatus.GRANTED }`. */ +inline fun FirebaseAnalytics.setConsent(block: ConsentBuilder.() -> Unit) { + setConsent(ConsentBuilder().apply(block).asMap()) +} + +/** The parameters of an event logged with [logEvent]. */ +class ParametersBuilder { + /** The parameters set so far, as a [Bundle] the block may also edit directly. */ + val bundle: Bundle = Bundle() + + fun param(key: String, value: Double) { + bundle.putDouble(key, value) + } + + fun param(key: String, value: Long) { + bundle.putLong(key, value) + } + + fun param(key: String, value: String) { + bundle.putString(key, value) + } + + fun param(key: String, value: Bundle) { + bundle.putBundle(key, value) + } + + /** An array of bundles, such as the [FirebaseAnalytics.Param.ITEMS] of an e-commerce event. */ + fun param(key: String, value: Array) { + bundle.putParcelableArray(key, value) + } +} + +/** The consent settings set with [setConsent]; a setting left null is not changed. */ +class ConsentBuilder { + var adStorage: FirebaseAnalytics.ConsentStatus? = null + var analyticsStorage: FirebaseAnalytics.ConsentStatus? = null + var adUserData: FirebaseAnalytics.ConsentStatus? = null + var adPersonalization: FirebaseAnalytics.ConsentStatus? = null + + /** The settings that were assigned. */ + fun asMap(): Map = buildMap { + adStorage?.let { put(FirebaseAnalytics.ConsentType.AD_STORAGE, it) } + analyticsStorage?.let { put(FirebaseAnalytics.ConsentType.ANALYTICS_STORAGE, it) } + adUserData?.let { put(FirebaseAnalytics.ConsentType.AD_USER_DATA, it) } + adPersonalization?.let { put(FirebaseAnalytics.ConsentType.AD_PERSONALIZATION, it) } + } +} diff --git a/src/main/java/com/google/firebase/analytics/FirebaseAnalytics.kt b/src/main/java/com/google/firebase/analytics/FirebaseAnalytics.kt new file mode 100644 index 0000000..63664a7 --- /dev/null +++ b/src/main/java/com/google/firebase/analytics/FirebaseAnalytics.kt @@ -0,0 +1,212 @@ +/* + * The entry point of Firebase Analytics, as the Android SDK's com.google.firebase.analytics.FirebaseAnalytics. Google + * Analytics has no client for the JVM, so this is a no-op: events, user properties and consent are accepted and dropped, + * and the identifiers are null. It exists so that code written against the Android SDK, such as firebase-kotlin-sdk's + * common code, compiles and runs on the JVM. + */ +package com.google.firebase.analytics + +import android.app.Activity +import android.content.Context +import android.os.Bundle +import com.google.android.gms.tasks.Task +import com.google.android.gms.tasks.Tasks + +/** + * The top level Firebase Analytics singleton, as in the Firebase Android SDK; obtained with [getInstance] or + * `Firebase.analytics`. Every call is a no-op on the JVM. + */ +class FirebaseAnalytics private constructor() { + + /** Logs an app event; the event is dropped on the JVM. See [Event] and [Param] for the recommended names. */ + fun logEvent(name: String, params: Bundle?) = Unit + + /** Deprecated in the Android SDK: sets the current screen. Log a [Event.SCREEN_VIEW] event instead. */ + @Deprecated("Log a SCREEN_VIEW event with the SCREEN_NAME and SCREEN_CLASS parameters instead") + fun setCurrentScreen(activity: Activity, screenName: String?, screenClassOverride: String?) = Unit + + /** Sets the parameters added to every event; null clears them. */ + fun setDefaultEventParameters(parameters: Bundle?) = Unit + + /** Sets a user property to the given value; null removes it. */ + fun setUserProperty(name: String, value: String?) = Unit + + /** Sets the applicable end user consent state. */ + fun setConsent(consentSettings: Map) = Unit + + /** Sets whether analytics collection is enabled for this app on this device. */ + fun setAnalyticsCollectionEnabled(enabled: Boolean) = Unit + + /** Sets the user ID property; null removes it. */ + fun setUserId(id: String?) = Unit + + /** Sets the duration of inactivity that terminates the current session, in milliseconds. */ + fun setSessionTimeoutDuration(milliseconds: Long) = Unit + + /** The app instance ID: a task completed with null, as the JVM has no analytics installation. */ + fun getAppInstanceId(): Task = Tasks.forResult(null) + + /** The Firebase Instance ID: always null on the JVM. */ + @Deprecated("Use getAppInstanceId()", ReplaceWith("getAppInstanceId()")) + fun getFirebaseInstanceId(): String? = null + + /** The session ID: a task completed with null, as the JVM has no analytics session. */ + fun getSessionId(): Task = Tasks.forResult(null) + + /** Clears all analytics data for this app from the device and resets the app instance ID. */ + fun resetAnalyticsData() = Unit + + override fun toString(): String = "FirebaseAnalytics" + + /** The recommended event names, as in the Android SDK. */ + open class Event protected constructor() { + companion object { + const val ADD_PAYMENT_INFO = "add_payment_info" + const val ADD_SHIPPING_INFO = "add_shipping_info" + const val ADD_TO_CART = "add_to_cart" + const val ADD_TO_WISHLIST = "add_to_wishlist" + const val AD_IMPRESSION = "ad_impression" + const val APP_OPEN = "app_open" + const val BEGIN_CHECKOUT = "begin_checkout" + const val CAMPAIGN_DETAILS = "campaign_details" + const val EARN_VIRTUAL_CURRENCY = "earn_virtual_currency" + const val GENERATE_LEAD = "generate_lead" + const val IN_APP_PURCHASE = "in_app_purchase" + const val JOIN_GROUP = "join_group" + const val LEVEL_END = "level_end" + const val LEVEL_START = "level_start" + const val LEVEL_UP = "level_up" + const val LOGIN = "login" + const val POST_SCORE = "post_score" + const val PURCHASE = "purchase" + const val REFUND = "refund" + const val REMOVE_FROM_CART = "remove_from_cart" + const val SCREEN_VIEW = "screen_view" + const val SEARCH = "search" + const val SELECT_CONTENT = "select_content" + const val SELECT_ITEM = "select_item" + const val SELECT_PROMOTION = "select_promotion" + const val SHARE = "share" + const val SIGN_UP = "sign_up" + const val SPEND_VIRTUAL_CURRENCY = "spend_virtual_currency" + const val TUTORIAL_BEGIN = "tutorial_begin" + const val TUTORIAL_COMPLETE = "tutorial_complete" + const val UNLOCK_ACHIEVEMENT = "unlock_achievement" + const val VIEW_CART = "view_cart" + const val VIEW_ITEM = "view_item" + const val VIEW_ITEM_LIST = "view_item_list" + const val VIEW_PROMOTION = "view_promotion" + const val VIEW_SEARCH_RESULTS = "view_search_results" + } + } + + /** The recommended parameter names, as in the Android SDK. */ + open class Param protected constructor() { + companion object { + const val ACHIEVEMENT_ID = "achievement_id" + const val ACLID = "aclid" + const val AD_FORMAT = "ad_format" + const val AD_PLATFORM = "ad_platform" + const val AD_SOURCE = "ad_source" + const val AD_UNIT_NAME = "ad_unit_name" + const val AFFILIATION = "affiliation" + const val CAMPAIGN = "campaign" + const val CAMPAIGN_ID = "campaign_id" + const val CHARACTER = "character" + const val CONTENT = "content" + const val CONTENT_TYPE = "content_type" + const val COUPON = "coupon" + const val CP1 = "cp1" + const val CREATIVE_FORMAT = "creative_format" + const val CREATIVE_NAME = "creative_name" + const val CREATIVE_SLOT = "creative_slot" + const val CURRENCY = "currency" + const val DESTINATION = "destination" + const val DISCOUNT = "discount" + const val END_DATE = "end_date" + const val EXTEND_SESSION = "extend_session" + const val FLIGHT_NUMBER = "flight_number" + const val FREE_TRIAL = "free_trial" + const val GROUP_ID = "group_id" + const val INDEX = "index" + const val ITEMS = "items" + const val ITEM_BRAND = "item_brand" + const val ITEM_CATEGORY = "item_category" + const val ITEM_CATEGORY2 = "item_category2" + const val ITEM_CATEGORY3 = "item_category3" + const val ITEM_CATEGORY4 = "item_category4" + const val ITEM_CATEGORY5 = "item_category5" + const val ITEM_ID = "item_id" + const val ITEM_LIST_ID = "item_list_id" + const val ITEM_LIST_NAME = "item_list_name" + const val ITEM_NAME = "item_name" + const val ITEM_VARIANT = "item_variant" + const val LEVEL = "level" + const val LEVEL_NAME = "level_name" + const val LOCATION = "location" + const val LOCATION_ID = "location_id" + const val MARKETING_TACTIC = "marketing_tactic" + const val MEDIUM = "medium" + const val METHOD = "method" + const val NUMBER_OF_NIGHTS = "number_of_nights" + const val NUMBER_OF_PASSENGERS = "number_of_passengers" + const val NUMBER_OF_ROOMS = "number_of_rooms" + const val ORIGIN = "origin" + const val PAYMENT_TYPE = "payment_type" + const val PRICE = "price" + const val PRICE_IS_DISCOUNTED = "price_is_discounted" + const val PRODUCT_ID = "product_id" + const val PRODUCT_NAME = "product_name" + const val PROMOTION_ID = "promotion_id" + const val PROMOTION_NAME = "promotion_name" + const val QUANTITY = "quantity" + const val SCORE = "score" + const val SCREEN_CLASS = "screen_class" + const val SCREEN_NAME = "screen_name" + const val SEARCH_TERM = "search_term" + const val SHIPPING = "shipping" + const val SHIPPING_TIER = "shipping_tier" + const val SOURCE = "source" + const val SOURCE_PLATFORM = "source_platform" + const val START_DATE = "start_date" + const val SUBSCRIPTION = "subscription" + const val SUCCESS = "success" + const val TAX = "tax" + const val TERM = "term" + const val TRANSACTION_ID = "transaction_id" + const val TRAVEL_CLASS = "travel_class" + const val VALUE = "value" + const val VIRTUAL_CURRENCY_NAME = "virtual_currency_name" + } + } + + /** The recommended user property names, as in the Android SDK. */ + open class UserProperty protected constructor() { + companion object { + const val ALLOW_AD_PERSONALIZATION_SIGNALS = "allow_personalized_ads" + const val SIGN_UP_METHOD = "sign_up_method" + } + } + + /** The type of consent to set, as in the Android SDK. */ + enum class ConsentType { + AD_STORAGE, + ANALYTICS_STORAGE, + AD_USER_DATA, + AD_PERSONALIZATION + } + + /** The status value of a consent type, as in the Android SDK. */ + enum class ConsentStatus { + GRANTED, + DENIED + } + + companion object { + private val instance = FirebaseAnalytics() + + /** The analytics singleton; the context is ignored on the JVM. */ + @JvmStatic + fun getInstance(context: Context): FirebaseAnalytics = instance + } +} diff --git a/src/main/java/com/google/firebase/messaging/FirebaseMessaging.kt b/src/main/java/com/google/firebase/messaging/FirebaseMessaging.kt new file mode 100644 index 0000000..ab46ead --- /dev/null +++ b/src/main/java/com/google/firebase/messaging/FirebaseMessaging.kt @@ -0,0 +1,75 @@ +/* + * Firebase Cloud Messaging, as the Android SDK's com.google.firebase.messaging.FirebaseMessaging. Messages are + * delivered to a device registration that the JVM does not have, so the singleton exists for code written against the + * Android SDK to compile and run, and every operation that needs a registration fails with an + * UnsupportedOperationException saying so. + */ +package com.google.firebase.messaging + +import com.google.android.gms.tasks.Task + +/** The top level Firebase Cloud Messaging singleton, as in the Firebase Android SDK; obtained with [getInstance] or `Firebase.messaging`. */ +class FirebaseMessaging private constructor() { + + /** + * Whether the registration token is generated automatically at startup; kept in memory, as there is no + * registration to initialise on the JVM. + */ + var isAutoInitEnabled: Boolean = true + + /** Deletes the registration token: unsupported on the JVM. */ + @Deprecated("Messages are received through a device registration, which the JVM does not have") + fun deleteToken(): Task = unsupported() + + /** The registration token: unsupported on the JVM. */ + @Deprecated("Messages are received through a device registration, which the JVM does not have") + fun getToken(): Task = unsupported() + + /** Sends an upstream message: decommissioned by Firebase Cloud Messaging, and unsupported on the JVM. */ + @Deprecated("Upstream messaging through Firebase Cloud Messaging was decommissioned in June 2024") + fun send(message: RemoteMessage): Unit = unsupported() + + /** Subscribes to a topic: unsupported on the JVM. */ + fun subscribeToTopic(topic: String): Task = unsupported() + + /** Unsubscribes from a topic: unsupported on the JVM. */ + fun unsubscribeFromTopic(topic: String): Task = unsupported() + + /** Whether message delivery metrics are exported to BigQuery: unsupported on the JVM. */ + fun deliveryMetricsExportToBigQueryEnabled(): Boolean = unsupported() + + /** Exports message delivery metrics to BigQuery: unsupported on the JVM. */ + fun setDeliveryMetricsExportToBigQuery(enable: Boolean): Unit = unsupported() + + /** Whether notifications are delegated to the device's proxy: unsupported on the JVM. */ + fun isNotificationDelegationEnabled(): Boolean = unsupported() + + /** Delegates notifications to the device's proxy: unsupported on the JVM. */ + fun setNotificationDelegationEnabled(enable: Boolean): Task = unsupported() + + /** Registers this app instance for messaging: unsupported on the JVM. */ + fun register(): Task = unsupported() + + /** Unregisters this app instance from messaging: unsupported on the JVM. */ + fun unregister(): Task = unsupported() + + override fun toString(): String = "FirebaseMessaging" + + companion object { + /** The scope of the registration token; a remnant of the Instance ID API. */ + @Deprecated("The registration token has no scope any more") + const val INSTANCE_ID_SCOPE = "FCM" + + private val instance = FirebaseMessaging() + + /** The messaging singleton. */ + @JvmStatic + fun getInstance(): FirebaseMessaging = instance + + internal const val UNSUPPORTED = + "Firebase Cloud Messaging is not available on the JVM: messages are received through a device registration " + + "with Google Play services or Apple Push Notification service, which a desktop or server JVM does not have" + + private fun unsupported(): Nothing = throw UnsupportedOperationException(UNSUPPORTED) + } +} diff --git a/src/main/java/com/google/firebase/messaging/FirebaseMessagingService.kt b/src/main/java/com/google/firebase/messaging/FirebaseMessagingService.kt new file mode 100644 index 0000000..6680d4b --- /dev/null +++ b/src/main/java/com/google/firebase/messaging/FirebaseMessagingService.kt @@ -0,0 +1,45 @@ +package com.google.firebase.messaging + +import android.app.Service +import android.content.Intent +import android.os.IBinder + +/** + * The service that receives messages and token refreshes on Android, as the Android SDK's FirebaseMessagingService. + * Nothing starts a service on the JVM, so a subclass compiles but its callbacks are never invoked. + */ +open class FirebaseMessagingService : Service() { + + /** Called with each message received while the app is in the foreground, or carrying data. */ + open fun onMessageReceived(message: RemoteMessage) = Unit + + /** Called when pending messages were deleted on the server before they could be delivered. */ + open fun onDeletedMessages() = Unit + + /** Called when an upstream message was sent. */ + @Deprecated("Upstream messaging through Firebase Cloud Messaging was decommissioned in June 2024") + open fun onMessageSent(msgId: String) = Unit + + /** Called when the registration token is created or refreshed. */ + @Deprecated("Use onRegistered") + open fun onNewToken(token: String) = Unit + + /** Called when this app instance is registered for messaging. */ + open fun onRegistered(token: String) = Unit + + /** Called when an upstream message could not be sent. */ + @Deprecated("Upstream messaging through Firebase Cloud Messaging was decommissioned in June 2024") + open fun onSendError(msgId: String, exception: Exception) = Unit + + /** Called when this app instance is unregistered from messaging. */ + open fun onUnregistered(token: String) = Unit + + fun onBind(intent: Intent?): IBinder? = null + + fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int = START_NOT_STICKY + + private companion object { + /** `android.app.Service.START_NOT_STICKY`. */ + const val START_NOT_STICKY = 2 + } +} diff --git a/src/main/java/com/google/firebase/messaging/Messaging.kt b/src/main/java/com/google/firebase/messaging/Messaging.kt new file mode 100644 index 0000000..f64a111 --- /dev/null +++ b/src/main/java/com/google/firebase/messaging/Messaging.kt @@ -0,0 +1,14 @@ +/* + * The Kotlin extensions the Android SDK's firebase-messaging ships as com.google.firebase.messaging.MessagingKt, so that + * code written against them compiles against this SDK like it does against the other ported libraries' facades. + */ +package com.google.firebase.messaging + +import com.google.firebase.Firebase + +/** Returns the [FirebaseMessaging] singleton. */ +val Firebase.messaging: FirebaseMessaging + get() = FirebaseMessaging.getInstance() + +/** Returns a [RemoteMessage] addressed to [to], initialized using the [init] function. */ +inline fun remoteMessage(to: String, init: RemoteMessage.Builder.() -> Unit): RemoteMessage = RemoteMessage.Builder(to).apply(init).build() diff --git a/src/main/java/com/google/firebase/messaging/RemoteMessage.kt b/src/main/java/com/google/firebase/messaging/RemoteMessage.kt new file mode 100644 index 0000000..0c7f247 --- /dev/null +++ b/src/main/java/com/google/firebase/messaging/RemoteMessage.kt @@ -0,0 +1,223 @@ +package com.google.firebase.messaging + +import android.net.Uri +import android.os.Bundle +import android.os.Parcel +import android.os.Parcelable + +/** + * A message received from, or (with [Builder]) sent to, Firebase Cloud Messaging, as the Android SDK's RemoteMessage: + * a [Bundle] of the message's fields, read through the keys the Android SDK uses. The JVM receives no messages, so an + * instance only comes from a [Builder]. + */ +class RemoteMessage internal constructor(private val bundle: Bundle) : Parcelable { + + private val applicationData: Map by lazy { + bundle.keySet().filter { it.isApplicationDataKey() }.associateWith { bundle.getString(it) ?: "" } + } + + private val notificationPayload: Notification? by lazy { + if (bundle.getString(KEY_NOTIFICATION_ENABLE) == "1" || bundle.keySet().any { it.startsWith(NOTIFICATION_PREFIX) }) Notification(bundle) else null + } + + /** The collapse key, if any. */ + val collapseKey: String? get() = bundle.getString(KEY_COLLAPSE_KEY) + + /** The application's data: every entry but the ones the SDK reserves (`google.*`, `gcm.*`, `from`, `message_type` and `collapse_key`). */ + val data: Map get() = applicationData + + /** The sender, if any. */ + val from: String? get() = bundle.getString(KEY_FROM) + + /** The message id, if any. */ + val messageId: String? get() = bundle.getString(KEY_MESSAGE_ID) ?: bundle.getString(KEY_MESSAGE_ID_LEGACY) + + /** The message type, if any. */ + val messageType: String? get() = bundle.getString(KEY_MESSAGE_TYPE) + + /** The notification payload, if the message carries one. */ + val notification: Notification? get() = notificationPayload + + /** The priority the message was sent with; one of the `PRIORITY_*` constants. */ + @get:MessagePriority + val originalPriority: Int get() = (bundle.getString(KEY_ORIGINAL_PRIORITY) ?: bundle.getString(KEY_PRIORITY)).toPriority() + + /** The priority the message was delivered with; one of the `PRIORITY_*` constants. */ + @get:MessagePriority + val priority: Int get() { + val delivered = bundle.getString(KEY_DELIVERED_PRIORITY) + return when { + delivered != null -> delivered.toPriority() + bundle.getString(KEY_PRIORITY_REDUCED) == "1" -> PRIORITY_NORMAL + else -> bundle.getString(KEY_PRIORITY).toPriority() + } + } + + /** The sender id. */ + @Deprecated("Use from instead", ReplaceWith("from")) + val senderId: String? get() = bundle.getString(KEY_SENDER_ID) + + /** When the message was sent, in milliseconds since the epoch; 0 when unknown. */ + val sentTime: Long get() = bundle.getString(KEY_SENT_TIME)?.toLongOrNull() ?: 0L + + /** The recipient. */ + @Deprecated("Upstream messaging through Firebase Cloud Messaging was decommissioned in June 2024") + val to: String? get() = bundle.getString(KEY_TO) + + /** The time to live in seconds; 0 when not set. */ + val ttl: Int get() = bundle.getString(KEY_TTL)?.toIntOrNull() ?: 0 + + override fun describeContents(): Int = 0 + + override fun writeToParcel(dest: Parcel, flags: Int) { + dest.writeBundle(bundle) + } + + private val entries: Map get() = bundle.keySet().associateWith { bundle.get(it) } + + override fun equals(other: Any?): Boolean = other is RemoteMessage && other.entries == entries + + override fun hashCode(): Int = entries.hashCode() + + @Suppress("DEPRECATION") + override fun toString(): String = "RemoteMessage(to=$to, messageId=$messageId, data=$applicationData)" + + /** Builds a [RemoteMessage] addressed to [to]. */ + class Builder(to: String) { + private val bundle = Bundle().apply { putString(KEY_TO, to) } + private val data = linkedMapOf() + + /** Adds a data entry; a null [value] removes the key. */ + fun addData(key: String, value: String?): Builder = apply { if (value == null) data.remove(key) else data[key] = value } + + fun build(): RemoteMessage = RemoteMessage(Bundle(bundle).apply { data.forEach { (key, value) -> putString(key, value) } }) + + /** Removes all data entries. */ + fun clearData(): Builder = apply { data.clear() } + + fun setCollapseKey(collapseKey: String?): Builder = apply { bundle.putString(KEY_COLLAPSE_KEY, collapseKey) } + + /** Replaces the data payload. */ + fun setData(data: Map): Builder = apply { + this.data.clear() + this.data.putAll(data) + } + + fun setMessageId(messageId: String): Builder = apply { bundle.putString(KEY_MESSAGE_ID, messageId) } + + fun setMessageType(messageType: String?): Builder = apply { bundle.putString(KEY_MESSAGE_TYPE, messageType) } + + /** The time to live in seconds, from 0 to 86400 (a day). */ + fun setTtl(ttl: Int): Builder = apply { bundle.putString(KEY_TTL, ttl.toString()) } + } + + /** The priorities of a message; the Android SDK's `@IntDef`. */ + @Retention(AnnotationRetention.SOURCE) + annotation class MessagePriority + + /** The notification payload of a message, read from the `gcm.n.*` entries like the Android SDK's RemoteMessage.Notification. */ + class Notification internal constructor(private val bundle: Bundle) { + private fun string(key: String): String? = bundle.getString(NOTIFICATION_PREFIX + key) ?: bundle.getString(NOTIFICATION_PREFIX_LEGACY + key) + private fun boolean(key: String): Boolean = string(key).let { it == "1" || it == "true" } + private fun int(key: String): Int? = string(key)?.toIntOrNull() + private fun strings(key: String): Array? = string(key)?.let { JsonArrays.strings(it) } + + val body: String? get() = string("body") + val bodyLocalizationArgs: Array? get() = strings("body_loc_args") + val bodyLocalizationKey: String? get() = string("body_loc_key") + val channelId: String? get() = string("android_channel_id") + val clickAction: String? get() = string("click_action") + val color: String? get() = string("color") + val defaultLightSettings: Boolean get() = boolean("default_light_settings") + val defaultSound: Boolean get() = boolean("default_sound") + val defaultVibrateSettings: Boolean get() = boolean("default_vibrate_timings") + val eventTime: Long? get() = string("event_time")?.let { JsonArrays.epochMillis(it) } + val icon: String? get() = string("icon") + val imageUrl: Uri? get() = string("image")?.takeIf { it.isNotEmpty() }?.let { Uri.parse(it) } + val lightSettings: IntArray? get() = strings("light_settings")?.takeIf { it.size == 3 }?.let { settings -> JsonArrays.lightSettings(settings) } + val link: Uri? get() = (string("link_android")?.takeIf { it.isNotEmpty() } ?: string("link"))?.takeIf { it.isNotEmpty() }?.let { Uri.parse(it) } + val localOnly: Boolean get() = boolean("local_only") + val notificationCount: Int? get() = int("notification_count") + val notificationPriority: Int? get() = int("notification_priority") + val sound: String? get() = string("sound2") ?: string("sound") + val sticky: Boolean get() = boolean("sticky") + val tag: String? get() = string("tag") + val ticker: String? get() = string("ticker") + val title: String? get() = string("title") + val titleLocalizationArgs: Array? get() = strings("title_loc_args") + val titleLocalizationKey: String? get() = string("title_loc_key") + val vibrateTimings: LongArray? get() = strings("vibrate_timings")?.mapNotNull { it.toLongOrNull() }?.toLongArray() + val visibility: Int? get() = int("visibility") + } + + companion object { + /** [getPriority]: not set. */ + const val PRIORITY_UNKNOWN = 0 + + /** [getPriority]: high. */ + const val PRIORITY_HIGH = 1 + + /** [getPriority]: normal. */ + const val PRIORITY_NORMAL = 2 + + @JvmField + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(source: Parcel): RemoteMessage = RemoteMessage(source.readBundle() ?: Bundle()) + override fun newArray(size: Int): Array = arrayOfNulls(size) + } + + // The keys the Android SDK stores the message's fields under. + private const val KEY_TO = "google.to" + private const val KEY_FROM = "from" + private const val KEY_MESSAGE_ID = "google.message_id" + private const val KEY_MESSAGE_ID_LEGACY = "message_id" + private const val KEY_MESSAGE_TYPE = "message_type" + private const val KEY_COLLAPSE_KEY = "collapse_key" + private const val KEY_TTL = "google.ttl" + private const val KEY_SENT_TIME = "google.sent_time" + private const val KEY_SENDER_ID = "google.c.sender.id" + private const val KEY_PRIORITY = "google.priority" + private const val KEY_ORIGINAL_PRIORITY = "google.original_priority" + private const val KEY_DELIVERED_PRIORITY = "google.delivered_priority" + private const val KEY_PRIORITY_REDUCED = "google.priority_reduced" + private const val KEY_NOTIFICATION_ENABLE = "gcm.n.e" + private const val NOTIFICATION_PREFIX = "gcm.n." + private const val NOTIFICATION_PREFIX_LEGACY = "gcm.notification." + + private fun String?.toPriority(): Int = when (this) { + "high" -> PRIORITY_HIGH + "normal" -> PRIORITY_NORMAL + else -> PRIORITY_UNKNOWN + } + + /** Whether a key is the application's, not one the SDK reserves (`google.*`, `gcm.*`, `from`, `message_type`, `collapse_key`). */ + private fun String.isApplicationDataKey(): Boolean = + !startsWith("google.") && !startsWith("gcm.") && this != KEY_FROM && this != KEY_MESSAGE_TYPE && this != KEY_COLLAPSE_KEY + } +} + +/** The JSON-array and timestamp encodings the notification payload uses, read with org.json like the Android SDK does. */ +private object JsonArrays { + fun strings(json: String): Array? = try { + val array = org.json.JSONArray(json) + Array(array.length()) { array.optString(it) } + } catch (e: org.json.JSONException) { + null + } + + /** The `light_settings`: an `#rrggbb` colour (as Android's opaque ARGB int) and the on and off durations in milliseconds. */ + fun lightSettings(settings: Array): IntArray? = try { + val hex = settings[0].removePrefix("#") + val color = hex.toLong(16).let { if (hex.length <= 6) it or 0xFF000000L else it }.toInt() + intArrayOf(color, settings[1].toInt(), settings[2].toInt()) + } catch (e: NumberFormatException) { + null + } + + /** An ISO-8601 `event_time`, as milliseconds since the epoch. */ + fun epochMillis(iso8601: String): Long? = try { + java.time.OffsetDateTime.parse(iso8601).toInstant().toEpochMilli() + } catch (e: java.time.format.DateTimeParseException) { + null + } +} diff --git a/src/main/java/com/google/firebase/messaging/SendException.kt b/src/main/java/com/google/firebase/messaging/SendException.kt new file mode 100644 index 0000000..afe083f --- /dev/null +++ b/src/main/java/com/google/firebase/messaging/SendException.kt @@ -0,0 +1,21 @@ +package com.google.firebase.messaging + +/** The failure of sending an upstream message, as the Android SDK's SendException; [errorCode] is one of the `ERROR_*` constants. */ +class SendException internal constructor(message: String?, val errorCode: Int) : Exception(message) { + companion object { + /** Unknown error. */ + const val ERROR_UNKNOWN = 0 + + /** The message parameters were invalid. */ + const val ERROR_INVALID_PARAMETERS = 1 + + /** The message was too large. */ + const val ERROR_SIZE = 2 + + /** The message's time to live was exceeded. */ + const val ERROR_TTL_EXCEEDED = 3 + + /** Too many messages were sent. */ + const val ERROR_TOO_MANY_MESSAGES = 4 + } +} diff --git a/src/main/java/com/google/firebase/perf/FirebasePerfRegistrar.java b/src/main/java/com/google/firebase/perf/FirebasePerfRegistrar.java new file mode 100644 index 0000000..4d707e4 --- /dev/null +++ b/src/main/java/com/google/firebase/perf/FirebasePerfRegistrar.java @@ -0,0 +1,27 @@ +package com.google.firebase.perf; + +import androidx.annotation.Keep; +import com.google.firebase.FirebaseApp; +import com.google.firebase.components.Component; +import com.google.firebase.components.ComponentRegistrar; +import com.google.firebase.components.Dependency; + +import java.util.Collections; +import java.util.List; + +/** + * Registers {@link FirebasePerformance} as a Firebase component, so that {@code app.get(FirebasePerformance.class)} + * works as with the Android SDK; the singleton is returned for every app. + */ +@Keep +public class FirebasePerfRegistrar implements ComponentRegistrar { + @Keep + public List> getComponents() { + return Collections.singletonList( + Component.builder(FirebasePerformance.class) + .add(Dependency.required(FirebaseApp.class)) + .factory(container -> FirebasePerformance.getInstance()) + .build() + ); + } +} diff --git a/src/main/java/com/google/firebase/perf/FirebasePerformance.kt b/src/main/java/com/google/firebase/perf/FirebasePerformance.kt new file mode 100644 index 0000000..41e617d --- /dev/null +++ b/src/main/java/com/google/firebase/perf/FirebasePerformance.kt @@ -0,0 +1,63 @@ +/* + * Firebase Performance Monitoring, as the Android SDK's com.google.firebase.perf.FirebasePerformance. There is no + * Performance Monitoring backend client for the JVM, so traces and HTTP metrics are kept in memory: they record their + * metrics and attributes, which code written against the Android SDK can read back, and report nothing. + */ +package com.google.firebase.perf + +import com.google.firebase.perf.metrics.HttpMetric +import com.google.firebase.perf.metrics.Trace +import java.net.URL + +/** The Firebase Performance Monitoring singleton, as in the Firebase Android SDK; obtained with [getInstance] or `Firebase.performance`. */ +class FirebasePerformance private constructor() { + + /** + * Whether performance monitoring is enabled. The Android SDK persists the setting; here it is kept in memory and + * does not affect the in-memory traces, which record their values either way. + */ + @Volatile + var isPerformanceCollectionEnabled: Boolean = true + + /** Creates a [Trace] with the given name. */ + fun newTrace(traceName: String): Trace = Trace(traceName) + + /** Creates an [HttpMetric] for a request of [httpMethod] (one of [HttpMethod]) to [url]. */ + fun newHttpMetric(url: String, @HttpMethod httpMethod: String): HttpMetric = HttpMetric(url, httpMethod) + + /** Creates an [HttpMetric] for a request of [httpMethod] (one of [HttpMethod]) to [url]. */ + fun newHttpMetric(url: URL, @HttpMethod httpMethod: String): HttpMetric = HttpMetric(url.toExternalForm(), httpMethod) + + override fun toString(): String = "FirebasePerformance" + + /** The HTTP method names accepted by [newHttpMetric]; the Android SDK's `@StringDef`. */ + @Retention(AnnotationRetention.SOURCE) + annotation class HttpMethod { + companion object { + const val GET = "GET" + const val PUT = "PUT" + const val POST = "POST" + const val DELETE = "DELETE" + const val HEAD = "HEAD" + const val PATCH = "PATCH" + const val OPTIONS = "OPTIONS" + const val TRACE = "TRACE" + const val CONNECT = "CONNECT" + } + } + + companion object { + /** Maximum length of a trace name. */ + const val MAX_TRACE_NAME_LENGTH = 100 + + private val instance = FirebasePerformance() + + /** The performance monitoring singleton, which [com.google.firebase.FirebaseApp.get] also returns for every app. */ + @JvmStatic + fun getInstance(): FirebasePerformance = instance + + /** Creates a [Trace] with the given name and starts it. */ + @JvmStatic + fun startTrace(traceName: String): Trace = Trace(traceName).apply { start() } + } +} diff --git a/src/main/java/com/google/firebase/perf/Performance.kt b/src/main/java/com/google/firebase/perf/Performance.kt new file mode 100644 index 0000000..6ab0caa --- /dev/null +++ b/src/main/java/com/google/firebase/perf/Performance.kt @@ -0,0 +1,36 @@ +/* + * The Kotlin extensions the Android SDK's firebase-perf ships as com.google.firebase.perf.PerformanceKt, so that code + * written against them compiles against this SDK like it does against the other ported libraries' facades. + */ +package com.google.firebase.perf + +import com.google.firebase.Firebase +import com.google.firebase.perf.metrics.HttpMetric +import com.google.firebase.perf.metrics.Trace + +/** Returns the [FirebasePerformance] singleton. */ +val Firebase.performance: FirebasePerformance + get() = FirebasePerformance.getInstance() + +/** Runs [block] between [HttpMetric.start] and [HttpMetric.stop] of this metric. */ +inline fun HttpMetric.trace(block: HttpMetric.() -> Unit) { + start() + try { + block() + } finally { + stop() + } +} + +/** Runs [block] between [Trace.start] and [Trace.stop] of this trace and returns its result. */ +inline fun Trace.trace(block: Trace.() -> T): T { + start() + try { + return block() + } finally { + stop() + } +} + +/** Creates a trace named [name], runs [block] between its start and stop and returns the result. */ +inline fun trace(name: String, block: Trace.() -> T): T = FirebasePerformance.getInstance().newTrace(name).trace(block) diff --git a/src/main/java/com/google/firebase/perf/metrics/AddTrace.kt b/src/main/java/com/google/firebase/perf/metrics/AddTrace.kt new file mode 100644 index 0000000..4b6a84e --- /dev/null +++ b/src/main/java/com/google/firebase/perf/metrics/AddTrace.kt @@ -0,0 +1,9 @@ +package com.google.firebase.perf.metrics + +/** + * Marks a method to be traced by the Firebase Performance Gradle plugin on Android, as the Android SDK's + * com.google.firebase.perf.metrics.AddTrace. Nothing reads it on the JVM. + */ +@Retention(AnnotationRetention.BINARY) +@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CONSTRUCTOR) +annotation class AddTrace(val name: String, val enabled: Boolean = true) diff --git a/src/main/java/com/google/firebase/perf/metrics/HttpMetric.kt b/src/main/java/com/google/firebase/perf/metrics/HttpMetric.kt new file mode 100644 index 0000000..a8aeb41 --- /dev/null +++ b/src/main/java/com/google/firebase/perf/metrics/HttpMetric.kt @@ -0,0 +1,117 @@ +package com.google.firebase.perf.metrics + +/** + * A metric of one HTTP request, as the Android SDK's com.google.firebase.perf.metrics.HttpMetric; created with + * [com.google.firebase.perf.FirebasePerformance.newHttpMetric]. Kept in memory: the values and attributes are + * recorded and nothing is reported. + */ +class HttpMetric internal constructor( + /** The request URL. */ + val url: String, + /** The HTTP method, one of [com.google.firebase.perf.FirebasePerformance.HttpMethod]. */ + val httpMethod: String +) { + private val customAttributes = linkedMapOf() + + /** The value last given to [setHttpResponseCode], or null. */ + @get:Synchronized + var httpResponseCode: Int? = null + private set + + /** The value last given to [setRequestPayloadSize], or null. */ + @get:Synchronized + var requestPayloadSize: Long? = null + private set + + /** The value last given to [setResponseContentType], or null. */ + @get:Synchronized + var responseContentType: String? = null + private set + + /** The value last given to [setResponsePayloadSize], or null. */ + @get:Synchronized + var responsePayloadSize: Long? = null + private set + + /** Whether [start] has been called. */ + @get:Synchronized + var isStarted: Boolean = false + private set + + /** Whether [stop] has been called. */ + @get:Synchronized + var isStopped: Boolean = false + private set + + /** The value of the custom attribute, or null if it is not set. */ + @Synchronized + fun getAttribute(attribute: String): String? = customAttributes[attribute] + + /** All custom attributes of this metric. */ + val attributes: Map + @Synchronized get() = customAttributes.toMap() + + /** Sets a custom attribute to the given value. */ + @Synchronized + fun putAttribute(attribute: String, value: String) { + customAttributes[attribute] = value + } + + /** Removes a custom attribute. */ + @Synchronized + fun removeAttribute(attribute: String) { + customAttributes.remove(attribute) + } + + /** Sets the HTTP response status code. */ + @Synchronized + fun setHttpResponseCode(responseCode: Int) { + httpResponseCode = responseCode + } + + /** Sets the size of the request payload in bytes. */ + @Synchronized + fun setRequestPayloadSize(bytes: Long) { + requestPayloadSize = bytes + } + + /** Sets the content type of the response. */ + @Synchronized + fun setResponseContentType(contentType: String?) { + responseContentType = contentType + } + + /** Sets the size of the response payload in bytes. */ + @Synchronized + fun setResponsePayloadSize(bytes: Long) { + responsePayloadSize = bytes + } + + /** Marks the start of the request. */ + @Synchronized + fun start() { + isStarted = true + } + + /** Marks the end of the response; on Android this reports the metric, here it only records that it ended. */ + @Synchronized + fun stop() { + if (isStarted) isStopped = true + } + + override fun toString(): String = "HttpMetric($httpMethod $url)" + + companion object { + /** Maximum length of a custom attribute key. */ + const val MAX_ATTRIBUTE_KEY_LENGTH = 40 + + /** Maximum length of a custom attribute value. */ + const val MAX_ATTRIBUTE_VALUE_LENGTH = 100 + + /** Maximum number of custom attributes. */ + const val MAX_TRACE_CUSTOM_ATTRIBUTES = 5 + + /** Maximum length of a trace name. */ + const val MAX_TRACE_NAME_LENGTH = 100 + } +} diff --git a/src/main/java/com/google/firebase/perf/metrics/Trace.kt b/src/main/java/com/google/firebase/perf/metrics/Trace.kt new file mode 100644 index 0000000..2f9d076 --- /dev/null +++ b/src/main/java/com/google/firebase/perf/metrics/Trace.kt @@ -0,0 +1,117 @@ +package com.google.firebase.perf.metrics + +import android.os.Parcel +import android.os.Parcelable + +/** + * A custom trace, as the Android SDK's com.google.firebase.perf.metrics.Trace: a period of time between [start] and + * [stop] with metrics and custom attributes; created with [com.google.firebase.perf.FirebasePerformance.newTrace]. + * Kept in memory: the metrics and attributes are recorded, atomically as the Android SDK's, and nothing is reported. + */ +class Trace internal constructor( + /** The name given to [com.google.firebase.perf.FirebasePerformance.newTrace]. */ + val name: String +) : Parcelable { + private val metrics = linkedMapOf() + private val customAttributes = linkedMapOf() + + /** Whether [start] has been called. */ + @get:Synchronized + var isStarted: Boolean = false + private set + + /** Whether [stop] has been called. */ + @get:Synchronized + var isStopped: Boolean = false + private set + + private val isRunning get() = isStarted && !isStopped + + /** Starts this trace. */ + @Synchronized + fun start() { + isStarted = true + } + + /** Stops this trace; on Android this reports it, here it only records that it ended. */ + @Synchronized + fun stop() { + if (isStarted) isStopped = true + } + + /** The value of the custom attribute, or null if it is not set. */ + @Synchronized + fun getAttribute(attribute: String): String? = customAttributes[attribute] + + /** All custom attributes of this trace. */ + val attributes: Map + @Synchronized get() = customAttributes.toMap() + + /** The value of the metric, or 0 if it has not been set; the metric is not created. */ + @Synchronized + fun getLongMetric(metricName: String): Long = metrics[metricName] ?: 0L + + /** + * Atomically increments the metric by [incrementBy], creating it if needed. Does nothing if the trace has not been + * started or has already been stopped. + */ + @Synchronized + fun incrementMetric(metricName: String, incrementBy: Long) { + if (isRunning) metrics[metricName] = getLongMetric(metricName) + incrementBy + } + + /** Sets a custom attribute to the given value. */ + @Synchronized + fun putAttribute(attribute: String, value: String) { + customAttributes[attribute] = value + } + + /** Sets the metric to [value], creating it if needed. Does nothing if the trace has not been started or has already been stopped. */ + @Synchronized + fun putMetric(metricName: String, value: Long) { + if (isRunning) metrics[metricName] = value + } + + /** Removes a custom attribute. */ + @Synchronized + fun removeAttribute(attribute: String) { + customAttributes.remove(attribute) + } + + override fun describeContents(): Int = 0 + + /** Writes the name, the metrics and the attributes; [CREATOR] reads them back into a trace that is neither started nor stopped. */ + @Synchronized + override fun writeToParcel(dest: Parcel, flags: Int) { + dest.writeString(name) + dest.writeMap(metrics) + dest.writeMap(customAttributes) + } + + override fun toString(): String = "Trace($name)" + + companion object { + /** Maximum length of a custom attribute key. */ + const val MAX_ATTRIBUTE_KEY_LENGTH = 40 + + /** Maximum length of a custom attribute value. */ + const val MAX_ATTRIBUTE_VALUE_LENGTH = 100 + + /** Maximum number of custom attributes. */ + const val MAX_TRACE_CUSTOM_ATTRIBUTES = 5 + + /** Maximum length of a trace name. */ + const val MAX_TRACE_NAME_LENGTH = 100 + + @JvmField + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + @Suppress("UNCHECKED_CAST") + override fun createFromParcel(source: Parcel): Trace = Trace(source.readString()!!).apply { + source.readMap(metrics as MutableMap, null) + source.readMap(customAttributes as MutableMap, null) + } + + override fun newArray(size: Int): Array = arrayOfNulls(size) + } + } +} diff --git a/src/test/kotlin/BundleTest.kt b/src/test/kotlin/BundleTest.kt index 0504c50..3d4083f 100644 --- a/src/test/kotlin/BundleTest.kt +++ b/src/test/kotlin/BundleTest.kt @@ -3,6 +3,9 @@ * Firebase libraries and firebase-kotlin-sdk's Analytics use. */ import android.os.Bundle +import android.os.Parcel +import com.google.firebase.Timestamp +import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull @@ -73,4 +76,37 @@ class BundleTest { target.clear() assertTrue(target.isEmpty()) } + + @Test + fun `stores parcelables and parcelable arrays`() { + val bundle = Bundle() + bundle.putParcelable("timestamp", Timestamp(1L, 2)) + bundle.putParcelableArray("items", arrayOf(Bundle().apply { putString("item_id", "SKU_1") }, Bundle().apply { putString("item_id", "SKU_2") })) + + assertEquals(Timestamp(1L, 2), bundle.getParcelable("timestamp")) + assertArrayEquals(arrayOf("SKU_1", "SKU_2"), bundle.getParcelableArray("items")!!.map { (it as Bundle).getString("item_id") }.toTypedArray()) + assertNull(bundle.getParcelable("items")) + assertNull(bundle.getParcelableArray("timestamp")) + } + + @Test + fun `is a parcelable written as its entries`() { + val bundle = Bundle().apply { + putString("string", "value") + putLong("long", 3L) + putBundle("nested", Bundle().apply { putBoolean("flag", true) }) + putParcelableArray("items", arrayOf(Bundle().apply { putInt("quantity", 2) })) + } + val parcel = Parcel.obtain() + parcel.writeParcelable(bundle, 0) + parcel.setDataPosition(0) + + val copy = parcel.readParcelable(null)!! + assertEquals(0, bundle.describeContents()) + assertEquals("value", copy.getString("string")) + assertEquals(3L, copy.getLong("long")) + assertTrue(copy.getBundle("nested")!!.getBoolean("flag")) + assertEquals(2, (copy.getParcelableArray("items")!!.single() as Bundle).getInt("quantity")) + assertEquals(bundle.keySet(), copy.keySet()) + } } diff --git a/src/test/kotlin/FirebaseAnalyticsTest.kt b/src/test/kotlin/FirebaseAnalyticsTest.kt new file mode 100644 index 0000000..da16d73 --- /dev/null +++ b/src/test/kotlin/FirebaseAnalyticsTest.kt @@ -0,0 +1,122 @@ +/* + * Tests the no-op com.google.firebase.analytics package: the singleton, its AnalyticsKt facade and that every call is + * accepted without effect, as Google Analytics has no client for the JVM. + */ +import android.app.Application +import android.os.Bundle +import com.google.android.gms.tasks.Tasks +import com.google.firebase.Firebase +import com.google.firebase.FirebaseApp +import com.google.firebase.analytics.ConsentBuilder +import com.google.firebase.analytics.FirebaseAnalytics +import com.google.firebase.analytics.ParametersBuilder +import com.google.firebase.analytics.analytics +import com.google.firebase.analytics.logEvent +import com.google.firebase.analytics.setConsent +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +class FirebaseAnalyticsTest : FirebaseTest() { + + @Test + fun `getInstance and the facade return the single instance`() { + val analytics = FirebaseAnalytics.getInstance(Application()) + assertSame(analytics, FirebaseAnalytics.getInstance(app.applicationContext)) + assertSame(analytics, Firebase.analytics) + } + + @Test + fun `the facade needs the default app, like the Android SDK`() { + FirebaseApp.clearInstancesForTest() + val exception = assertThrows(IllegalStateException::class.java) { Firebase.analytics } + assertTrue(exception.message!!.startsWith("Default FirebaseApp is not initialized")) + } + + @Test + fun `every operation is a no-op that does not throw`() { + val analytics = FirebaseAnalytics.getInstance(Application()) + analytics.logEvent(FirebaseAnalytics.Event.LOGIN, Bundle().apply { putString(FirebaseAnalytics.Param.METHOD, "email") }) + analytics.logEvent(FirebaseAnalytics.Event.APP_OPEN, null) + analytics.setDefaultEventParameters(Bundle().apply { putString("default_key", "default_value") }) + analytics.setDefaultEventParameters(null) + analytics.setUserProperty(FirebaseAnalytics.UserProperty.SIGN_UP_METHOD, "email") + analytics.setUserProperty("gone", null) + analytics.setUserId("user") + analytics.setUserId(null) + analytics.setAnalyticsCollectionEnabled(false) + analytics.setAnalyticsCollectionEnabled(true) + analytics.setSessionTimeoutDuration(1_800_000L) + analytics.setConsent(mapOf(FirebaseAnalytics.ConsentType.AD_STORAGE to FirebaseAnalytics.ConsentStatus.DENIED)) + @Suppress("DEPRECATION") + analytics.setCurrentScreen(android.app.Activity(), "screen", null) + analytics.resetAnalyticsData() + + assertNull(Tasks.await(analytics.getAppInstanceId())) + assertNull(Tasks.await(analytics.getSessionId())) + @Suppress("DEPRECATION") + assertNull(analytics.getFirebaseInstanceId()) + } + + @Test + fun `the facade builders collect parameters and consent`() { + val analytics = FirebaseAnalytics.getInstance(app.applicationContext) + analytics.logEvent(FirebaseAnalytics.Event.PURCHASE) { + param(FirebaseAnalytics.Param.CURRENCY, "USD") + param(FirebaseAnalytics.Param.VALUE, 12.5) + param(FirebaseAnalytics.Param.QUANTITY, 2L) + param(FirebaseAnalytics.Param.ITEMS, arrayOf(Bundle().apply { putString(FirebaseAnalytics.Param.ITEM_ID, "SKU_1") })) + } + analytics.setConsent { + adStorage = FirebaseAnalytics.ConsentStatus.GRANTED + analyticsStorage = FirebaseAnalytics.ConsentStatus.DENIED + } + + val parameters = ParametersBuilder().apply { + param("string", "value") + param("double", 1.5) + param("long", 2L) + param("bundle", Bundle().apply { putInt("nested", 3) }) + param("items", arrayOf(Bundle().apply { putString("item_id", "SKU_1") }, Bundle().apply { putString("item_id", "SKU_2") })) + }.bundle + assertEquals("value", parameters.getString("string")) + assertEquals(1.5, parameters.getDouble("double"), 0.0) + assertEquals(2L, parameters.getLong("long")) + assertEquals(3, parameters.getBundle("bundle")?.getInt("nested")) + assertArrayEquals(arrayOf("SKU_1", "SKU_2"), parameters.getParcelableArray("items")!!.map { (it as Bundle).getString("item_id") }.toTypedArray()) + + val consent = ConsentBuilder().apply { + adUserData = FirebaseAnalytics.ConsentStatus.GRANTED + adPersonalization = FirebaseAnalytics.ConsentStatus.DENIED + }.asMap() + assertEquals( + mapOf( + FirebaseAnalytics.ConsentType.AD_USER_DATA to FirebaseAnalytics.ConsentStatus.GRANTED, + FirebaseAnalytics.ConsentType.AD_PERSONALIZATION to FirebaseAnalytics.ConsentStatus.DENIED + ), + consent + ) + assertEquals(emptyMap(), ConsentBuilder().asMap()) + } + + @Test + fun `constants have the Android SDK values`() { + assertEquals("purchase", FirebaseAnalytics.Event.PURCHASE) + assertEquals("screen_view", FirebaseAnalytics.Event.SCREEN_VIEW) + assertEquals("view_search_results", FirebaseAnalytics.Event.VIEW_SEARCH_RESULTS) + assertEquals("currency", FirebaseAnalytics.Param.CURRENCY) + assertEquals("item_category5", FirebaseAnalytics.Param.ITEM_CATEGORY5) + assertEquals("virtual_currency_name", FirebaseAnalytics.Param.VIRTUAL_CURRENCY_NAME) + assertEquals("allow_personalized_ads", FirebaseAnalytics.UserProperty.ALLOW_AD_PERSONALIZATION_SIGNALS) + assertEquals("sign_up_method", FirebaseAnalytics.UserProperty.SIGN_UP_METHOD) + assertEquals( + listOf("AD_STORAGE", "ANALYTICS_STORAGE", "AD_USER_DATA", "AD_PERSONALIZATION"), + FirebaseAnalytics.ConsentType.values().map { it.name } + ) + assertEquals(listOf("GRANTED", "DENIED"), FirebaseAnalytics.ConsentStatus.values().map { it.name }) + } +} diff --git a/src/test/kotlin/FirebaseMessagingTest.kt b/src/test/kotlin/FirebaseMessagingTest.kt new file mode 100644 index 0000000..515af5c --- /dev/null +++ b/src/test/kotlin/FirebaseMessagingTest.kt @@ -0,0 +1,242 @@ +/* + * Tests the com.google.firebase.messaging package: the singleton whose operations are unsupported on the JVM, the + * in-memory RemoteMessage with its Builder and Notification, and the MessagingKt facade. + */ +import android.os.Bundle +import android.os.Parcel +import com.google.firebase.Firebase +import com.google.firebase.messaging.FirebaseMessaging +import com.google.firebase.messaging.FirebaseMessagingService +import com.google.firebase.messaging.RemoteMessage +import com.google.firebase.messaging.SendException +import com.google.firebase.messaging.messaging +import com.google.firebase.messaging.remoteMessage +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +class FirebaseMessagingTest { + + @Test + fun `getInstance and the facade return the single instance`() { + assertSame(FirebaseMessaging.getInstance(), FirebaseMessaging.getInstance()) + assertSame(FirebaseMessaging.getInstance(), Firebase.messaging) + } + + @Test + fun `auto init is kept in memory`() { + val messaging = Firebase.messaging + messaging.isAutoInitEnabled = false + assertFalse(messaging.isAutoInitEnabled) + messaging.isAutoInitEnabled = true + assertTrue(messaging.isAutoInitEnabled) + } + + @Test + fun `operations needing a registration are unsupported`() { + val messaging = Firebase.messaging + val message = remoteMessage("846484016111@fcm.googleapis.com") { setMessageId("id") } + + @Suppress("DEPRECATION") + val operations = listOf<() -> Any?>( + { messaging.getToken() }, + { messaging.deleteToken() }, + { messaging.subscribeToTopic("news") }, + { messaging.unsubscribeFromTopic("news") }, + { messaging.send(message) }, + { messaging.deliveryMetricsExportToBigQueryEnabled() }, + { messaging.setDeliveryMetricsExportToBigQuery(true) }, + { messaging.isNotificationDelegationEnabled() }, + { messaging.setNotificationDelegationEnabled(true) }, + { messaging.register() }, + { messaging.unregister() } + ) + operations.forEach { operation -> + val exception = assertThrows(UnsupportedOperationException::class.java) { operation() } + assertTrue(exception.message!!.startsWith("Firebase Cloud Messaging is not available on the JVM")) + } + } + + @Test + fun `the builder round trips a message`() { + val message: RemoteMessage = remoteMessage("846484016111@fcm.googleapis.com") { + addData("first", "one") + addData("second", "two") + addData("first", null) + setMessageId("compat-id") + setMessageType("compat-type") + setCollapseKey("compat-key") + setTtl(60) + } + assertEquals(mapOf("second" to "two"), message.data) + assertEquals("compat-id", message.messageId) + assertEquals("compat-type", message.messageType) + assertEquals("compat-key", message.collapseKey) + assertEquals(60, message.ttl) + @Suppress("DEPRECATION") + assertEquals("846484016111@fcm.googleapis.com", message.to) + assertEquals(RemoteMessage.PRIORITY_UNKNOWN, message.priority) + assertEquals(RemoteMessage.PRIORITY_UNKNOWN, message.originalPriority) + assertNull(message.notification) + assertNull(message.from) + @Suppress("DEPRECATION") + assertNull(message.senderId) + assertEquals(0L, message.sentTime) + + val replaced = RemoteMessage.Builder("846484016111@fcm.googleapis.com").setData(mapOf("a" to "b")).clearData().addData("c", "d").build() + assertEquals(mapOf("c" to "d"), replaced.data) + assertEquals(0, replaced.ttl) + assertNull(replaced.messageId) + + // getData() leaves out the keys the SDK reserves. + val reserved = RemoteMessage.Builder("846484016111@fcm.googleapis.com") + .addData("google.c.a.e", "1") + .addData("gcm.n.e", "1") + .addData("from", "sender") + .addData("message_type", "gcm") + .addData("collapse_key", "key") + .addData("application", "value") + .build() + assertEquals(mapOf("application" to "value"), reserved.data) + + val same = remoteMessage("846484016111@fcm.googleapis.com") { + addData("second", "two") + setMessageId("compat-id") + setMessageType("compat-type") + setCollapseKey("compat-key") + setTtl(60) + } + assertEquals(message, same) + assertEquals(message.hashCode(), same.hashCode()) + assertNotEquals(message, replaced) + } + + @Test + fun `a received message reads its fields and notification from the bundle like the Android SDK`() { + val message = RemoteMessage( + Bundle().apply { + putString("from", "846484016111") + putString("google.message_id", "0:123") + putString("google.c.sender.id", "846484016111") + putString("google.sent_time", "1700000000000") + putString("google.ttl", "2419200") + putString("google.original_priority", "high") + putString("google.delivered_priority", "normal") + putString("gcm.n.e", "1") + putString("gcm.n.title", "Title") + putString("gcm.n.body", "Body") + putString("gcm.n.icon", "ic_notification") + putString("gcm.n.sound2", "chime") + putString("gcm.n.tag", "tag") + putString("gcm.n.color", "#ff0000") + putString("gcm.n.click_action", "OPEN") + putString("gcm.n.android_channel_id", "channel") + putString("gcm.n.link", "https://example.com/page") + putString("gcm.n.image", "https://example.com/image.png") + putString("gcm.n.ticker", "ticker") + putString("gcm.n.sticky", "1") + putString("gcm.n.local_only", "true") + putString("gcm.n.default_sound", "1") + putString("gcm.n.default_vibrate_timings", "0") + putString("gcm.n.default_light_settings", "1") + putString("gcm.n.notification_priority", "2") + putString("gcm.n.visibility", "1") + putString("gcm.n.notification_count", "3") + putString("gcm.n.event_time", "2023-11-14T22:13:20Z") + putString("gcm.n.vibrate_timings", "[100, 200]") + putString("gcm.n.light_settings", "[\"#00ff00\", \"300\", \"400\"]") + putString("gcm.n.title_loc_key", "title_key") + putString("gcm.n.title_loc_args", "[\"a\", \"b\"]") + putString("gcm.n.body_loc_key", "body_key") + putString("gcm.n.body_loc_args", "[\"c\"]") + putString("key", "value") + } + ) + assertEquals("846484016111", message.from) + assertEquals("0:123", message.messageId) + @Suppress("DEPRECATION") + assertEquals("846484016111", message.senderId) + assertEquals(1700000000000L, message.sentTime) + assertEquals(2419200, message.ttl) + assertEquals(RemoteMessage.PRIORITY_HIGH, message.originalPriority) + assertEquals(RemoteMessage.PRIORITY_NORMAL, message.priority) + assertEquals(mapOf("key" to "value"), message.data) + + val notification = message.notification!! + assertEquals("Title", notification.title) + assertEquals("Body", notification.body) + assertEquals("ic_notification", notification.icon) + assertEquals("chime", notification.sound) + assertEquals("tag", notification.tag) + assertEquals("#ff0000", notification.color) + assertEquals("OPEN", notification.clickAction) + assertEquals("channel", notification.channelId) + assertEquals("https://example.com/page", notification.link.toString()) + assertEquals("https://example.com/image.png", notification.imageUrl.toString()) + assertEquals("ticker", notification.ticker) + assertTrue(notification.sticky) + assertTrue(notification.localOnly) + assertTrue(notification.defaultSound) + assertFalse(notification.defaultVibrateSettings) + assertTrue(notification.defaultLightSettings) + assertEquals(2, notification.notificationPriority) + assertEquals(1, notification.visibility) + assertEquals(3, notification.notificationCount) + assertEquals(1700000000000L, notification.eventTime) + assertArrayEquals(longArrayOf(100, 200), notification.vibrateTimings) + assertArrayEquals(intArrayOf(0xFF00FF00.toInt(), 300, 400), notification.lightSettings) + assertEquals("title_key", notification.titleLocalizationKey) + assertArrayEquals(arrayOf("a", "b"), notification.titleLocalizationArgs) + assertEquals("body_key", notification.bodyLocalizationKey) + assertArrayEquals(arrayOf("c"), notification.bodyLocalizationArgs) + + val plain = RemoteMessage(Bundle().apply { putString("google.priority", "high") }) + assertEquals(RemoteMessage.PRIORITY_HIGH, plain.priority) + assertEquals(RemoteMessage.PRIORITY_HIGH, plain.originalPriority) + assertNull(plain.notification) + assertEquals(RemoteMessage.PRIORITY_NORMAL, RemoteMessage(Bundle().apply { putString("google.priority", "high"); putString("google.priority_reduced", "1") }).priority) + } + + @Test + fun `a message round trips through a parcel`() { + val message = remoteMessage("846484016111@fcm.googleapis.com") { + addData("key", "value") + setMessageId("id") + setTtl(10) + } + val parcel = Parcel.obtain() + parcel.writeParcelable(message, 0) + parcel.setDataPosition(0) + assertEquals(message, parcel.readParcelable(null)) + } + + @Test + fun `constants have the Android SDK values and a service subclass compiles`() { + assertEquals(1, RemoteMessage.PRIORITY_HIGH) + assertEquals(2, RemoteMessage.PRIORITY_NORMAL) + assertEquals(0, RemoteMessage.PRIORITY_UNKNOWN) + assertEquals(0, SendException.ERROR_UNKNOWN) + assertEquals(1, SendException.ERROR_INVALID_PARAMETERS) + assertEquals(2, SendException.ERROR_SIZE) + assertEquals(3, SendException.ERROR_TTL_EXCEEDED) + assertEquals(4, SendException.ERROR_TOO_MANY_MESSAGES) + @Suppress("DEPRECATION") + assertEquals("FCM", FirebaseMessaging.INSTANCE_ID_SCOPE) + + val received = mutableListOf() + val service = object : FirebaseMessagingService() { + override fun onMessageReceived(message: RemoteMessage) { + received += message.messageId!! + } + } + service.onMessageReceived(remoteMessage("to") { setMessageId("id") }) + service.onDeletedMessages() + assertEquals(listOf("id"), received) + } +} diff --git a/src/test/kotlin/FirebasePerformanceTest.kt b/src/test/kotlin/FirebasePerformanceTest.kt new file mode 100644 index 0000000..276958f --- /dev/null +++ b/src/test/kotlin/FirebasePerformanceTest.kt @@ -0,0 +1,186 @@ +/* + * Tests the in-memory com.google.firebase.perf package: the singleton (also a Firebase component), traces that record + * metrics and attributes, HTTP metrics that record their values, and the PerformanceKt facade. + */ +import android.os.Parcel +import com.google.firebase.Firebase +import com.google.firebase.perf.FirebasePerformance +import com.google.firebase.perf.metrics.AddTrace +import com.google.firebase.perf.metrics.HttpMetric +import com.google.firebase.perf.metrics.Trace +import com.google.firebase.perf.performance +import com.google.firebase.perf.trace +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import java.net.URL +import kotlin.concurrent.thread + +class FirebasePerformanceTest : FirebaseTest() { + + @Test + fun `getInstance, the facade and the Firebase component return the single instance`() { + val performance = FirebasePerformance.getInstance() + assertSame(performance, FirebasePerformance.getInstance()) + assertSame(performance, Firebase.performance) + assertSame(performance, app.get(FirebasePerformance::class.java)) + } + + @Test + fun `collection enabled is kept in memory`() { + val performance = Firebase.performance + performance.isPerformanceCollectionEnabled = false + assertFalse(performance.isPerformanceCollectionEnabled) + performance.isPerformanceCollectionEnabled = true + assertTrue(performance.isPerformanceCollectionEnabled) + } + + @Test + fun `a trace records metrics while running and attributes at any time`() { + val trace: Trace = Firebase.performance.newTrace("compat_trace") + assertEquals("compat_trace", trace.name) + trace.putMetric("early", 1) + trace.incrementMetric("early", 1) + assertEquals(0L, trace.getLongMetric("early")) // not started yet + trace.putAttribute("before", "start") + + trace.start() + assertTrue(trace.isStarted) + trace.putMetric("requests", 2) + trace.incrementMetric("requests", 3) + trace.incrementMetric("created", 4) + assertEquals(5L, trace.getLongMetric("requests")) + assertEquals(4L, trace.getLongMetric("created")) + assertEquals(0L, trace.getLongMetric("missing")) + trace.putAttribute("first", "one") + trace.putAttribute("second", "two") + assertEquals("one", trace.getAttribute("first")) + assertEquals(mapOf("before" to "start", "first" to "one", "second" to "two"), trace.attributes) + trace.removeAttribute("first") + assertNull(trace.getAttribute("first")) + trace.stop() + assertTrue(trace.isStopped) + + trace.putMetric("requests", 100) + trace.incrementMetric("requests", 100) + assertEquals(5L, trace.getLongMetric("requests")) // stopped + trace.putAttribute("after", "stop") + assertEquals(mapOf("before" to "start", "second" to "two", "after" to "stop"), trace.attributes) + } + + @Test + fun `startTrace and the trace blocks start and stop the trace`() { + val started = FirebasePerformance.startTrace("compat_started") + assertTrue(started.isStarted) + started.putMetric("count", 1) + assertEquals(1L, started.getLongMetric("count")) + started.stop() + + var inBlock: Trace? = null + val fromBlock = trace("compat_block") { + inBlock = this + putMetric("count", 7) + getLongMetric("count") + } + assertEquals(7L, fromBlock) + assertTrue(inBlock!!.isStopped) + + val fromTraceBlock = Firebase.performance.newTrace("compat_trace_block").trace { + putAttribute("key", "value") + getAttribute("key") + } + assertEquals("value", fromTraceBlock) + + var inMetricBlock: HttpMetric? = null + Firebase.performance.newHttpMetric("https://example.com/", FirebasePerformance.HttpMethod.POST).trace { + inMetricBlock = this + setHttpResponseCode(201) + } + assertEquals(201, inMetricBlock!!.httpResponseCode) + assertTrue(inMetricBlock!!.isStopped) + } + + @Test + fun `an http metric records its values`() { + val metric: HttpMetric = Firebase.performance.newHttpMetric("https://example.com/data.json", FirebasePerformance.HttpMethod.GET) + assertEquals("https://example.com/data.json", metric.url) + assertEquals("GET", metric.httpMethod) + metric.start() + metric.putAttribute("first", "one") + metric.putAttribute("second", "two") + assertEquals("one", metric.getAttribute("first")) + assertEquals(mapOf("first" to "one", "second" to "two"), metric.attributes) + metric.removeAttribute("first") + assertNull(metric.getAttribute("first")) + metric.setHttpResponseCode(200) + metric.setRequestPayloadSize(0) + metric.setResponsePayloadSize(1024) + metric.setResponseContentType("application/json") + metric.stop() + assertEquals(200, metric.httpResponseCode) + assertEquals(0L, metric.requestPayloadSize) + assertEquals(1024L, metric.responsePayloadSize) + assertEquals("application/json", metric.responseContentType) + assertTrue(metric.isStarted) + assertTrue(metric.isStopped) + + val fromUrl = Firebase.performance.newHttpMetric(URL("https://example.com/data.json"), FirebasePerformance.HttpMethod.PUT) + assertEquals("https://example.com/data.json", fromUrl.url) + assertEquals("PUT", fromUrl.httpMethod) + assertNull(fromUrl.httpResponseCode) + } + + @Test + fun `a trace increments atomically from several threads`() { + val trace = FirebasePerformance.getInstance().newTrace("concurrent").apply { start() } + val threads = List(8) { thread { repeat(1_000) { trace.incrementMetric("hits", 1) } } } + threads.forEach { it.join() } + trace.stop() + assertEquals(8_000L, trace.getLongMetric("hits")) + } + + @Test + fun `a trace round trips its name, metrics and attributes through a parcel`() { + val trace = FirebasePerformance.startTrace("parcelled").apply { + putMetric("count", 3) + putAttribute("key", "value") + stop() + } + val parcel = Parcel.obtain() + parcel.writeParcelable(trace, 0) + parcel.setDataPosition(0) + val copy = parcel.readParcelable(null)!! + assertEquals("parcelled", copy.name) + assertEquals(3L, copy.getLongMetric("count")) + assertEquals(mapOf("key" to "value"), copy.attributes) + assertFalse(copy.isStarted) + } + + @Test + fun `constants have the Android SDK values`() { + assertEquals(100, FirebasePerformance.MAX_TRACE_NAME_LENGTH) + assertEquals(40, Trace.MAX_ATTRIBUTE_KEY_LENGTH) + assertEquals(100, Trace.MAX_ATTRIBUTE_VALUE_LENGTH) + assertEquals(5, Trace.MAX_TRACE_CUSTOM_ATTRIBUTES) + assertEquals(100, Trace.MAX_TRACE_NAME_LENGTH) + assertEquals(40, HttpMetric.MAX_ATTRIBUTE_KEY_LENGTH) + assertEquals(100, HttpMetric.MAX_ATTRIBUTE_VALUE_LENGTH) + assertEquals(5, HttpMetric.MAX_TRACE_CUSTOM_ATTRIBUTES) + assertEquals(100, HttpMetric.MAX_TRACE_NAME_LENGTH) + assertEquals( + listOf("GET", "PUT", "POST", "DELETE", "HEAD", "PATCH", "OPTIONS", "TRACE", "CONNECT"), + listOf( + FirebasePerformance.HttpMethod.GET, FirebasePerformance.HttpMethod.PUT, FirebasePerformance.HttpMethod.POST, + FirebasePerformance.HttpMethod.DELETE, FirebasePerformance.HttpMethod.HEAD, FirebasePerformance.HttpMethod.PATCH, + FirebasePerformance.HttpMethod.OPTIONS, FirebasePerformance.HttpMethod.TRACE, FirebasePerformance.HttpMethod.CONNECT + ) + ) + assertEquals("compat_annotated", annotated()) + } + + @AddTrace(name = "compat_annotated") + private fun annotated(): String = "compat_annotated" +} diff --git a/src/test/kotlin/ParcelTest.kt b/src/test/kotlin/ParcelTest.kt index 145f84b..17d031c 100644 --- a/src/test/kotlin/ParcelTest.kt +++ b/src/test/kotlin/ParcelTest.kt @@ -193,4 +193,17 @@ class ParcelTest { assertEquals(5, parcel.readInt()) assertFalse(parcel.dataAvail() > 0) } + + @Test + fun `round trips parcelable arrays as values and directly`() { + val parcel = Parcel.obtain() + parcel.writeParcelableArray(arrayOf(Timestamp(1L, 2), Timestamp(3L, 4)), 0) + parcel.writeParcelableArray(null, 0) + parcel.writeValue(arrayOf(Uri.parse("https://example.com/a"))) + parcel.setDataPosition(0) + + assertArrayEquals(arrayOf(Timestamp(1L, 2), Timestamp(3L, 4)), parcel.readParcelableArray(null)) + assertNull(parcel.readParcelableArray(null)) + assertArrayEquals(arrayOf(Uri.parse("https://example.com/a")), parcel.readValue(null) as Array<*>) + } }